From 67c1e89d90ef576e62f8b1c68269742a3c6f9b1e Mon Sep 17 00:00:00 2001 From: Konstantin Bogdanov Date: Thu, 19 Sep 2024 13:51:02 +0200 Subject: [PATCH] Apply linter changes --- .clang-tidy | 1 - base/base/DecomposedFloat.h | 11 +- base/base/JSON.cpp | 33 +- base/base/JSON.h | 6 +- base/base/StringRef.h | 6 +- base/base/argsToConfig.cpp | 7 +- base/base/find_symbols.h | 6 +- base/base/getMemoryAmount.cpp | 3 +- programs/benchmark/Benchmark.cpp | 14 +- programs/client/Client.cpp | 32 +- programs/disks/CommandCopy.cpp | 4 +- programs/disks/CommandList.cpp | 8 +- programs/disks/CommandMove.cpp | 6 +- programs/disks/CommandRemove.cpp | 8 +- programs/disks/CommandWrite.cpp | 10 +- programs/disks/DisksApp.cpp | 104 ++-- programs/disks/DisksClient.cpp | 41 +- programs/disks/ICommand.cpp | 8 +- programs/disks/ICommand.h | 24 +- programs/install/Install.cpp | 4 +- .../CatBoostLibraryHandlerFactory.cpp | 16 +- .../LibraryBridgeHandlerFactory.cpp | 4 +- .../library-bridge/LibraryBridgeHandlers.cpp | 8 +- programs/obfuscator/Obfuscator.cpp | 8 +- programs/odbc-bridge/getIdentifierQuote.cpp | 10 +- .../validateODBCConnectionString.cpp | 14 +- src/Access/AccessBackup.cpp | 6 +- src/Access/AccessControl.cpp | 7 +- src/Access/AccessRights.cpp | 30 +- src/Access/AuthenticationData.cpp | 7 +- src/Access/Common/AccessFlags.cpp | 3 +- src/Access/Common/AllowedClientHosts.cpp | 14 +- src/Access/Common/QuotaDefs.cpp | 6 +- src/Access/ContextAccess.cpp | 33 +- src/Access/ContextAccessParams.cpp | 19 +- src/Access/KerberosInit.cpp | 3 +- src/Access/LDAPAccessStorage.cpp | 5 +- src/Access/QuotaCache.cpp | 3 +- src/Access/RolesOrUsersSet.cpp | 10 +- src/Access/SettingsAuthResponseParser.cpp | 2 +- src/Access/SettingsConstraints.cpp | 21 +- src/Access/UsersConfigAccessStorage.cpp | 3 +- .../AggregateFunctionAnyRespectNulls.cpp | 4 +- .../AggregateFunctionDeltaSum.cpp | 5 +- .../AggregateFunctionFactory.cpp | 17 +- .../AggregateFunctionFlameGraph.cpp | 24 +- .../AggregateFunctionGroupArray.cpp | 7 +- .../AggregateFunctionGroupArrayIntersect.cpp | 21 +- .../AggregateFunctionGroupArrayMoving.cpp | 20 +- .../AggregateFunctionGroupArraySorted.cpp | 11 +- .../AggregateFunctionGroupBitmap.cpp | 3 +- .../AggregateFunctionGroupBitmapData.h | 60 +- .../AggregateFunctionGroupConcat.cpp | 3 +- .../AggregateFunctionGroupUniqArray.cpp | 22 +- .../AggregateFunctionMaxIntersections.cpp | 3 +- .../AggregateFunctionQuantileGK.cpp | 15 +- .../AggregateFunctionSequenceMatch.cpp | 2 +- .../AggregateFunctionStatistics.cpp | 19 +- .../AggregateFunctionSumMap.cpp | 21 +- .../AggregateFunctionTTest.h | 27 +- .../AggregateFunctionTopK.cpp | 17 +- .../AggregateFunctionUniq.cpp | 80 +-- .../AggregateFunctionUniqCombined.h | 47 +- .../AggregateFunctionUniqUpTo.cpp | 18 +- .../AggregateFunctionWindowFunnel.cpp | 12 +- .../Combinators/AggregateFunctionDistinct.cpp | 6 +- .../Combinators/AggregateFunctionIf.cpp | 30 +- .../Combinators/AggregateFunctionMap.cpp | 5 +- .../Combinators/AggregateFunctionNull.cpp | 30 +- .../Combinators/AggregateFunctionOrFill.cpp | 3 +- src/AggregateFunctions/DDSketch.h | 8 +- src/AggregateFunctions/IAggregateFunction.h | 2 +- src/AggregateFunctions/QuantileExact.h | 4 +- src/AggregateFunctions/QuantileTDigest.h | 11 +- src/AggregateFunctions/QuantileTiming.h | 8 +- src/AggregateFunctions/ReservoirSampler.h | 6 +- .../ReservoirSamplerDeterministic.h | 3 +- src/AggregateFunctions/SingleValueData.cpp | 117 ++-- src/AggregateFunctions/ThetaSketchData.h | 5 +- src/AggregateFunctions/UniqVariadicHash.cpp | 3 +- src/Analyzer/ColumnTransformers.cpp | 22 +- src/Analyzer/FunctionNode.cpp | 4 +- src/Analyzer/IQueryTreeNode.cpp | 8 +- src/Analyzer/InDepthQueryTreeVisitor.h | 3 +- src/Analyzer/MatcherNode.cpp | 4 +- ...egateFunctionsArithmericOperationsPass.cpp | 5 +- src/Analyzer/Passes/CNF.cpp | 3 +- src/Analyzer/Passes/ConvertQueryToCNFPass.cpp | 2 +- .../Passes/IfTransformStringsToEnumPass.cpp | 3 +- ...ateOrDateTimeConverterWithPreimagePass.cpp | 11 +- src/Analyzer/Resolve/IdentifierResolver.cpp | 14 +- src/Analyzer/Resolve/QueryAnalyzer.cpp | 36 +- .../Resolve/QueryExpressionsAliasVisitor.h | 4 +- src/Analyzer/SortNode.cpp | 4 +- src/Analyzer/UnionNode.cpp | 2 +- src/Analyzer/Utils.cpp | 14 +- src/Analyzer/ValidationUtils.cpp | 4 +- src/Backups/BackupEntriesCollector.cpp | 23 +- src/Backups/BackupEntryFromAppendOnlyFile.cpp | 5 +- src/Backups/BackupEntryFromImmutableFile.cpp | 3 +- src/Backups/BackupIO_Default.cpp | 3 +- src/Backups/BackupIO_File.cpp | 2 +- src/Backups/BackupImpl.cpp | 14 +- src/Backups/BackupsWorker.cpp | 24 +- .../registerBackupEngineAzureBlobStorage.cpp | 45 +- src/Backups/registerBackupEngineS3.cpp | 48 +- .../registerBackupEnginesFileAndDisk.cpp | 36 +- src/BridgeHelper/XDBCBridgeHelper.h | 3 +- src/Client/ClientBase.cpp | 3 +- src/Client/ClientBaseHelpers.cpp | 2 +- src/Client/HedgedConnections.cpp | 2 +- src/Client/LineReader.cpp | 3 +- src/Client/LocalConnection.cpp | 2 +- src/Client/Suggest.cpp | 2 +- src/Client/TestHint.cpp | 3 +- src/Client/TestHint.h | 5 +- src/Columns/ColumnAggregateFunction.cpp | 18 +- src/Columns/ColumnConst.cpp | 2 +- src/Columns/ColumnDynamic.cpp | 33 +- src/Columns/ColumnLowCardinality.cpp | 16 +- src/Columns/ColumnNullable.cpp | 15 +- src/Columns/ColumnTuple.cpp | 5 +- src/Columns/ColumnUnique.h | 3 +- src/Columns/ColumnVariant.cpp | 4 +- src/Columns/ColumnVector.cpp | 3 +- src/Columns/ColumnsCommon.h | 11 +- src/Columns/IColumn.cpp | 6 +- src/Common/Allocator.cpp | 14 +- src/Common/ArenaAllocator.h | 12 +- src/Common/AsyncLoader.cpp | 3 +- src/Common/AsynchronousMetrics.cpp | 21 +- src/Common/BufferAllocationPolicy.cpp | 3 +- src/Common/COW.h | 3 +- src/Common/CalendarTimeInterval.cpp | 12 +- src/Common/CancelToken.cpp | 11 +- src/Common/CaresPTRResolver.cpp | 2 +- src/Common/CombinedCardinalityEstimator.h | 7 +- src/Common/CompactArray.h | 9 +- src/Common/ConcurrencyControl.cpp | 6 +- .../AbstractConfigurationComparison.cpp | 30 +- src/Common/Config/ConfigProcessor.cpp | 46 +- src/Common/CounterInFile.h | 3 +- src/Common/CurrentMemoryTracker.cpp | 10 +- src/Common/DNSResolver.cpp | 4 +- src/Common/DateLUTImpl.cpp | 8 +- src/Common/DateLUTImpl.h | 41 +- src/Common/Dwarf.cpp | 72 +-- src/Common/Elf.cpp | 3 +- src/Common/Epoll.cpp | 6 +- src/Common/FailPoint.cpp | 13 +- src/Common/FieldVisitorConvertToNumber.h | 2 +- src/Common/HashTable/HashTable.h | 6 +- src/Common/HashTable/StringHashTable.h | 3 +- src/Common/HilbertUtils.h | 17 +- src/Common/HyperLogLogBiasEstimator.h | 26 +- src/Common/HyperLogLogCounter.h | 12 +- src/Common/IFactoryWithAliases.h | 7 +- src/Common/InterruptListener.h | 3 +- src/Common/LRUResourceCache.h | 12 +- src/Common/Macros.cpp | 7 +- src/Common/MemoryTracker.cpp | 20 +- src/Common/MemoryWorker.cpp | 8 +- .../NamedCollectionsFactory.cpp | 2 +- .../NamedCollectionsMetadataStorage.cpp | 12 +- src/Common/NetlinkMetricsProvider.cpp | 3 +- src/Common/OptimizedRegularExpression.cpp | 161 +++-- src/Common/OvercommitTracker.cpp | 3 +- src/Common/PODArray.h | 4 +- src/Common/PageCache.cpp | 3 +- src/Common/PoolBase.h | 12 +- src/Common/PoolWithFailoverBase.h | 5 +- src/Common/ProxyConfiguration.h | 2 +- .../ProxyConfigurationResolverProvider.cpp | 4 +- src/Common/QueryFuzzer.cpp | 20 +- src/Common/RadixSort.h | 14 +- src/Common/Scheduler/ISchedulerNode.h | 26 +- .../Scheduler/Nodes/ClassifiersConfig.cpp | 3 +- .../Nodes/DynamicResourceManager.cpp | 3 +- src/Common/Scheduler/Nodes/FairPolicy.h | 3 +- src/Common/Scheduler/Nodes/PriorityPolicy.h | 3 +- .../Scheduler/Nodes/SemaphoreConstraint.h | 3 +- .../Scheduler/Nodes/ThrottlerConstraint.h | 3 +- src/Common/Scheduler/SchedulerRoot.h | 4 +- src/Common/SignalHandlers.cpp | 9 +- src/Common/StatusFile.cpp | 3 +- src/Common/StudentTTest.cpp | 8 +- src/Common/SymbolIndex.cpp | 6 +- src/Common/SystemLogBase.cpp | 3 +- src/Common/ThreadFuzzer.cpp | 4 +- src/Common/ThreadProfileEvents.cpp | 2 +- src/Common/UTF8Helpers.cpp | 8 +- src/Common/VersionNumber.cpp | 2 +- src/Common/Volnitsky.h | 2 + src/Common/ZooKeeper/ZooKeeper.cpp | 163 +++-- src/Common/ZooKeeper/ZooKeeperImpl.cpp | 17 +- .../assertProcessUserMatchesDataOwner.cpp | 6 +- src/Common/checkStackSize.cpp | 3 +- src/Common/examples/check_pointer_valid.cpp | 8 +- src/Common/examples/lru_hash_map_perf.cpp | 12 +- src/Common/getNumberOfCPUCoresToUse.cpp | 3 +- src/Common/memcmpSmall.h | 2 +- src/Common/memory.h | 23 +- src/Common/mysqlxx/Pool.cpp | 6 +- src/Common/mysqlxx/PoolFactory.cpp | 37 +- src/Common/mysqlxx/PoolWithFailover.cpp | 4 +- src/Common/mysqlxx/mysqlxx/Pool.h | 3 +- src/Common/mysqlxx/mysqlxx/Value.h | 21 +- src/Common/parseAddress.cpp | 10 +- src/Common/remapExecutable.cpp | 4 +- src/Common/typeid_cast.h | 6 +- src/Compression/CompressedReadBufferBase.cpp | 8 +- .../CompressionCodecDeflateQpl.cpp | 37 +- src/Compression/CompressionCodecDelta.cpp | 7 +- .../CompressionCodecDoubleDelta.cpp | 19 +- src/Compression/CompressionCodecEncrypted.cpp | 28 +- src/Compression/CompressionCodecFPC.cpp | 13 +- src/Compression/CompressionCodecGCD.cpp | 9 +- src/Compression/CompressionCodecGorilla.cpp | 7 +- src/Compression/CompressionCodecT64.cpp | 6 +- src/Compression/CompressionFactory.cpp | 13 +- .../CompressionFactoryAdditions.cpp | 6 +- src/Compression/ICompressionCodec.cpp | 4 +- src/Compression/LZ4_decompress_faster.cpp | 6 +- src/Compression/LZ4_decompress_faster.h | 6 +- src/Coordination/Changelog.cpp | 2 +- src/Coordination/FourLetterCommand.cpp | 19 +- src/Coordination/KeeperContext.cpp | 12 +- src/Coordination/KeeperDispatcher.cpp | 23 +- src/Coordination/KeeperServer.cpp | 16 +- src/Coordination/KeeperSnapshotManager.cpp | 13 +- src/Coordination/KeeperStateMachine.cpp | 10 +- src/Coordination/KeeperStateManager.cpp | 27 +- src/Coordination/KeeperStorage.cpp | 6 +- src/Coordination/RocksDBContainer.h | 5 +- src/Core/BackgroundSchedulePool.cpp | 10 +- src/Core/BaseSettings.h | 16 +- src/Core/DecimalComparison.h | 2 +- src/Core/Joins.h | 6 +- src/Core/MySQL/IMySQLWritePacket.cpp | 10 +- src/Core/MySQL/MySQLClient.cpp | 2 +- src/Core/MySQL/MySQLReplication.cpp | 4 +- src/Core/PostgreSQL/insertPostgreSQLValue.cpp | 2 +- src/Core/QualifiedTableName.h | 6 +- src/Core/SettingsFields.cpp | 28 +- src/Core/SortCursor.h | 4 +- src/Daemon/BaseDaemon.cpp | 6 +- src/Daemon/BaseDaemon.h | 3 +- src/DataTypes/DataTypeDecimalBase.h | 6 +- src/DataTypes/DataTypeEnum.cpp | 13 +- src/DataTypes/DataTypeFactory.cpp | 3 +- src/DataTypes/DataTypeLowCardinality.cpp | 18 +- .../DataTypeLowCardinalityHelpers.cpp | 3 +- src/DataTypes/DataTypeTuple.cpp | 5 +- src/DataTypes/DataTypesDecimal.cpp | 3 +- src/DataTypes/EnumValues.cpp | 20 +- src/DataTypes/IDataType.h | 6 +- src/DataTypes/Native.cpp | 57 +- src/DataTypes/NestedUtils.cpp | 6 +- src/DataTypes/ObjectUtils.cpp | 38 +- .../Serializations/ISerialization.cpp | 5 +- .../Serializations/SerializationArray.cpp | 27 +- .../Serializations/SerializationDynamic.cpp | 2 +- .../Serializations/SerializationInfo.cpp | 2 +- .../SerializationLowCardinality.cpp | 10 +- .../Serializations/SerializationMap.cpp | 11 +- .../Serializations/SerializationTuple.cpp | 110 ++-- .../Serializations/SerializationVariant.cpp | 4 +- src/DataTypes/getLeastSupertype.cpp | 63 +- src/DataTypes/getMostSubtype.cpp | 50 +- src/DataTypes/hasNullable.cpp | 4 +- src/DataTypes/registerDataTypeDateTime.cpp | 6 +- src/Databases/DatabaseFactory.cpp | 3 +- src/Databases/DatabaseFilesystem.cpp | 6 +- src/Databases/DatabaseMemory.cpp | 3 +- src/Databases/DatabaseOnDisk.cpp | 24 +- src/Databases/DatabaseReplicated.cpp | 9 +- src/Databases/DatabaseReplicatedWorker.cpp | 2 +- src/Databases/DatabasesCommon.cpp | 6 +- src/Databases/IDatabase.cpp | 15 +- .../MySQL/MaterializedMySQLSyncThread.cpp | 5 +- src/Databases/MySQL/MySQLBinlog.cpp | 2 +- src/Databases/SQLite/SQLiteUtils.cpp | 3 +- src/Dictionaries/CacheDictionary.cpp | 64 +- src/Dictionaries/CacheDictionaryStorage.h | 3 +- .../ClickHouseDictionarySource.cpp | 22 +- src/Dictionaries/DictionaryHelpers.h | 12 +- src/Dictionaries/DictionaryStructure.cpp | 5 +- src/Dictionaries/DirectDictionary.cpp | 16 +- .../GeodataProviders/NamesProvider.cpp | 3 +- src/Dictionaries/ExternalQueryBuilder.cpp | 116 ++-- src/Dictionaries/HashedArrayDictionary.cpp | 14 +- .../HierarchyDictionariesUtils.cpp | 10 +- src/Dictionaries/MySQLDictionarySource.cpp | 8 +- .../PostgreSQLDictionarySource.cpp | 8 +- src/Dictionaries/RegExpTreeDictionary.cpp | 10 +- src/Dictionaries/RegExpTreeDictionary.h | 10 +- src/Dictionaries/SSDCacheDictionaryStorage.h | 6 +- src/Dictionaries/XDBCDictionarySource.cpp | 8 +- src/Dictionaries/registerHashedDictionary.cpp | 47 +- src/Disks/DiskEncrypted.cpp | 12 +- src/Disks/DiskEncrypted.h | 6 +- src/Disks/DiskLocal.cpp | 13 +- .../IO/AsynchronousBoundedReadBuffer.cpp | 2 +- .../IO/CachedOnDiskReadBufferFromFile.cpp | 25 +- src/Disks/IO/IOUringReader.cpp | 20 +- src/Disks/IO/ThreadPoolReader.cpp | 24 +- .../IO/WriteBufferFromAzureBlobStorage.cpp | 6 +- .../ObjectStorages/DiskObjectStorage.cpp | 7 +- ...torageFromPlainRewritableObjectStorage.cpp | 3 +- .../ObjectStorages/ObjectStorageFactory.cpp | 5 +- .../ObjectStorages/StaticDirectoryIterator.h | 3 +- .../ObjectStorages/Web/WebObjectStorage.cpp | 44 +- .../ObjectStorages/Web/WebObjectStorage.h | 6 +- src/Disks/StoragePolicy.cpp | 3 +- src/Disks/VolumeJBOD.cpp | 3 +- src/Formats/EscapingRuleUtils.cpp | 17 +- src/Formats/FormatSchemaInfo.cpp | 23 +- src/Formats/JSONUtils.cpp | 15 +- src/Formats/ProtobufSchemas.cpp | 22 +- src/Formats/ProtobufSerializer.cpp | 65 +- src/Formats/SchemaInferenceUtils.cpp | 2 +- src/Functions/CastOverloadResolver.cpp | 15 +- src/Functions/DateTimeTransforms.h | 94 ++- src/Functions/FunctionBase64Conversion.h | 2 +- src/Functions/FunctionBinaryArithmetic.h | 53 +- src/Functions/FunctionBitTestMany.h | 26 +- .../FunctionCustomWeekToDateOrDate32.h | 45 +- src/Functions/FunctionCustomWeekToSomething.h | 22 +- .../FunctionDateOrDateTimeAddInterval.h | 27 +- .../FunctionDateOrDateTimeToDateOrDate32.h | 31 +- ...tionDateOrDateTimeToDateTimeOrDateTime64.h | 31 +- .../FunctionDateOrDateTimeToSomething.h | 18 +- src/Functions/FunctionFactory.cpp | 3 +- src/Functions/FunctionHelpers.cpp | 11 +- src/Functions/FunctionMathUnary.h | 3 +- src/Functions/FunctionSQLJSON.h | 8 +- src/Functions/FunctionStringOrArrayToT.h | 31 +- src/Functions/FunctionStringReplace.h | 51 +- src/Functions/FunctionStringToString.h | 7 +- src/Functions/FunctionTokens.h | 11 +- src/Functions/FunctionsAES.h | 14 +- .../FunctionsBinaryRepresentation.cpp | 52 +- src/Functions/FunctionsBitToArray.cpp | 6 +- src/Functions/FunctionsBitmap.h | 76 ++- src/Functions/FunctionsCodingIP.cpp | 15 +- src/Functions/FunctionsCodingIP.h | 8 +- src/Functions/FunctionsCodingUUID.cpp | 34 +- src/Functions/FunctionsComparison.h | 228 ++++--- src/Functions/FunctionsConsistentHashing.h | 4 +- src/Functions/FunctionsDecimalArithmetics.h | 63 +- src/Functions/FunctionsEmbeddedDictionaries.h | 39 +- src/Functions/FunctionsExternalDictionaries.h | 27 +- src/Functions/FunctionsHashing.h | 63 +- src/Functions/FunctionsLogical.cpp | 3 +- src/Functions/FunctionsStringDistance.cpp | 14 +- .../FunctionsStringHashFixedString.cpp | 12 +- src/Functions/FunctionsStringSearch.h | 3 +- src/Functions/FunctionsStringSearchToString.h | 5 +- src/Functions/FunctionsTimeWindow.cpp | 77 ++- src/Functions/FunctionsTimeWindow.h | 13 +- .../FunctionsTonalityClassification.cpp | 3 +- src/Functions/GregorianDate.cpp | 13 +- src/Functions/HasTokenImpl.h | 7 +- src/Functions/IFunction.cpp | 8 +- src/Functions/IFunctionCustomWeek.h | 12 +- src/Functions/IFunctionDateOrDateTime.h | 33 +- src/Functions/LeftRight.h | 39 +- src/Functions/MatchImpl.h | 29 +- src/Functions/PositionImpl.h | 26 +- src/Functions/Regexps.h | 4 +- .../URL/FirstSignificantSubdomainCustomImpl.h | 5 +- src/Functions/URL/URLHierarchy.cpp | 3 +- src/Functions/URL/URLPathHierarchy.cpp | 3 +- src/Functions/URL/cutURLParameter.cpp | 6 +- src/Functions/URL/decodeURLComponent.cpp | 2 +- src/Functions/URL/extractURLParameter.cpp | 8 +- .../URL/extractURLParameterNames.cpp | 3 +- src/Functions/URL/netloc.cpp | 7 +- src/Functions/URL/port.cpp | 5 +- src/Functions/UTCTimestampTransform.cpp | 5 +- ...alUserDefinedExecutableFunctionsLoader.cpp | 2 +- .../UserDefinedSQLObjectsDiskStorage.cpp | 5 +- .../UserDefinedSQLObjectsStorageBase.cpp | 5 +- .../UserDefinedSQLObjectsZooKeeperStorage.cpp | 5 +- .../createUserDefinedSQLObjectsStorage.cpp | 10 +- src/Functions/addressToLine.h | 6 +- src/Functions/appendTrailingCharIfAbsent.cpp | 5 +- src/Functions/array/FunctionArrayMapped.h | 66 +- src/Functions/array/arrayAll.cpp | 24 +- src/Functions/array/arrayCount.cpp | 3 +- src/Functions/array/arrayCumSum.cpp | 3 +- .../array/arrayCumSumNonNegative.cpp | 3 +- src/Functions/array/arrayDifference.cpp | 3 +- src/Functions/array/arrayDistance.cpp | 2 +- src/Functions/array/arrayDotProduct.cpp | 2 +- src/Functions/array/arrayElement.cpp | 96 ++- src/Functions/array/arrayEnumerate.cpp | 8 +- src/Functions/array/arrayExists.cpp | 3 +- src/Functions/array/arrayFilter.cpp | 5 +- src/Functions/array/arrayFirstLast.cpp | 20 +- src/Functions/array/arrayFirstLastIndex.cpp | 6 +- src/Functions/array/arrayIndex.h | 158 +++-- src/Functions/array/arrayIntersect.cpp | 15 +- src/Functions/array/arrayJaccardIndex.cpp | 6 +- src/Functions/array/arrayResize.cpp | 4 +- src/Functions/array/arrayReverse.cpp | 9 +- src/Functions/array/arraySlice.cpp | 2 +- src/Functions/array/arrayZip.cpp | 5 +- src/Functions/array/emptyArrayToSingle.cpp | 15 +- src/Functions/array/mapOp.cpp | 5 +- src/Functions/array/mapPopulateSeries.cpp | 3 +- src/Functions/array/range.cpp | 3 +- src/Functions/assumeNotNull.cpp | 3 +- src/Functions/bitShiftLeft.cpp | 4 +- src/Functions/bitShiftRight.cpp | 4 +- src/Functions/bitSlice.cpp | 11 +- src/Functions/checkHyperscanRegexp.cpp | 2 +- src/Functions/concat.cpp | 7 +- src/Functions/convertCharset.cpp | 4 +- src/Functions/countDigits.cpp | 3 +- src/Functions/countMatches.h | 7 +- src/Functions/date_trunc.cpp | 22 +- src/Functions/decodeHTMLComponent.cpp | 20 +- src/Functions/encodeXMLComponent.cpp | 2 +- .../extractTimeZoneFromFunctionArguments.cpp | 44 +- src/Functions/filesystem.cpp | 36 +- src/Functions/formatDateTime.cpp | 74 ++- src/Functions/formatQuery.cpp | 15 +- src/Functions/formatReadableTimeDelta.cpp | 30 +- src/Functions/formatRow.cpp | 3 +- src/Functions/fromModifiedJulianDay.cpp | 5 +- src/Functions/fuzzBits.cpp | 14 +- src/Functions/geometryConverters.h | 10 +- src/Functions/getScalar.cpp | 2 +- src/Functions/getSizeOfEnumType.cpp | 7 +- src/Functions/globalVariable.cpp | 3 +- src/Functions/greatCircleDistance.cpp | 29 +- src/Functions/if.cpp | 74 +-- src/Functions/isDecimalOverflow.cpp | 2 +- src/Functions/isIPAddressContainedIn.cpp | 14 +- src/Functions/isNotNull.cpp | 8 +- src/Functions/isNull.cpp | 10 +- .../keyvaluepair/ArgumentExtractor.cpp | 2 +- .../keyvaluepair/impl/StateHandlerImpl.h | 6 +- src/Functions/minSampleSize.cpp | 8 +- src/Functions/neighbor.cpp | 63 +- src/Functions/normalizedQueryHash.cpp | 5 +- src/Functions/overlay.cpp | 14 +- src/Functions/parseDateTime.cpp | 58 +- src/Functions/parseReadableSize.cpp | 21 +- src/Functions/pointInEllipses.cpp | 22 +- src/Functions/pointInPolygon.cpp | 98 ++- src/Functions/printf.cpp | 34 +- src/Functions/repeat.cpp | 23 +- src/Functions/reverse.cpp | 16 +- src/Functions/runningDifference.h | 3 +- src/Functions/seriesOutliersDetectTukey.cpp | 8 +- src/Functions/splitByRegexp.cpp | 5 +- src/Functions/stl.hpp | 68 ++- src/Functions/stringCutToZero.cpp | 12 +- src/Functions/substring.cpp | 22 +- src/Functions/substringIndex.cpp | 38 +- src/Functions/svg.cpp | 2 +- src/Functions/throwIf.cpp | 8 +- src/Functions/timeSlots.cpp | 69 ++- src/Functions/timezoneOf.cpp | 3 +- src/Functions/toLowCardinality.cpp | 10 +- src/Functions/transform.cpp | 29 +- src/Functions/translate.cpp | 17 +- src/Functions/tuple.h | 3 +- src/Functions/tupleElement.cpp | 30 +- src/Functions/variantElement.cpp | 3 +- src/Functions/widthBucket.cpp | 2 +- src/IO/Archives/LibArchiveWriter.cpp | 3 +- src/IO/Archives/ZipArchiveWriter.cpp | 15 +- ...ynchronousReadBufferFromFileDescriptor.cpp | 2 +- .../copyAzureBlobStorageFile.cpp | 12 +- src/IO/BrotliReadBuffer.cpp | 9 +- src/IO/CompressionMethod.cpp | 17 +- src/IO/ConnectionTimeouts.cpp | 3 +- src/IO/FileEncryptionCommon.cpp | 13 +- src/IO/HadoopSnappyReadBuffer.cpp | 2 +- src/IO/HashingWriteBuffer.h | 3 +- src/IO/LZMAInflatingReadBuffer.cpp | 16 +- src/IO/ReadBufferFromFileDescriptor.cpp | 2 + src/IO/ReadBufferFromMemory.cpp | 21 +- src/IO/ReadBufferFromPocoSocketChunked.cpp | 3 +- src/IO/ReadBufferFromS3.cpp | 8 +- src/IO/ReadHelpers.cpp | 13 +- src/IO/ReadHelpers.h | 35 +- src/IO/ReadWriteBufferFromHTTP.cpp | 16 +- src/IO/S3/AWSLogger.cpp | 3 +- src/IO/S3/Credentials.cpp | 31 +- src/IO/S3/PocoHTTPClientFactory.cpp | 4 +- src/IO/S3/copyS3File.cpp | 30 +- src/IO/S3/getObjectInfo.cpp | 8 +- src/IO/StdStreamBufFromReadBuffer.cpp | 10 +- src/IO/WithFileName.cpp | 7 +- src/IO/WithFileSize.cpp | 8 +- src/IO/WriteBufferFromArena.h | 5 +- src/IO/WriteHelpers.h | 23 +- src/IO/ZlibInflatingReadBuffer.cpp | 17 +- src/IO/ZstdDeflatingAppendableWriteBuffer.cpp | 5 +- src/IO/parseDateTimeBestEffort.cpp | 142 +++-- src/IO/readDecimalText.h | 51 +- src/IO/readFloatText.h | 4 +- src/Interpreters/ActionsVisitor.cpp | 29 +- src/Interpreters/Aggregator.cpp | 27 +- .../ArithmeticOperationsInAgrFuncOptimize.cpp | 5 +- src/Interpreters/ArrayJoinAction.cpp | 10 +- src/Interpreters/AsynchronousInsertQueue.cpp | 2 +- src/Interpreters/AsynchronousInsertQueue.h | 3 +- src/Interpreters/BloomFilter.cpp | 3 +- src/Interpreters/BloomFilterHash.h | 72 ++- src/Interpreters/Cache/EvictionCandidates.cpp | 3 +- .../Cache/LRUFileCachePriority.cpp | 6 +- src/Interpreters/Cache/Metadata.cpp | 25 +- .../Cache/SLRUFileCachePriority.cpp | 9 +- .../Cache/WriteBufferToFileSegment.cpp | 9 +- src/Interpreters/Cluster.cpp | 98 ++- .../ClusterProxy/SelectStreamFactory.cpp | 9 +- src/Interpreters/ComparisonGraph.cpp | 34 +- src/Interpreters/Context.cpp | 27 +- src/Interpreters/DDLTask.cpp | 44 +- src/Interpreters/DDLWorker.cpp | 49 +- src/Interpreters/DatabaseCatalog.cpp | 56 +- src/Interpreters/ExternalLoader.cpp | 15 +- src/Interpreters/GlobalSubqueriesVisitor.h | 4 +- .../HashJoin/HashJoinMethodsImpl.h | 11 +- src/Interpreters/IdentifierSemantic.cpp | 5 +- src/Interpreters/InterpreterAlterQuery.cpp | 2 +- src/Interpreters/InterpreterCheckQuery.cpp | 8 +- .../InterpreterCreateIndexQuery.cpp | 8 +- src/Interpreters/InterpreterCreateQuery.cpp | 39 +- src/Interpreters/InterpreterDeleteQuery.cpp | 20 +- src/Interpreters/InterpreterDropQuery.cpp | 50 +- src/Interpreters/InterpreterExplainQuery.cpp | 18 +- .../InterpreterExternalDDLQuery.cpp | 18 +- src/Interpreters/InterpreterInsertQuery.cpp | 5 +- src/Interpreters/InterpreterRenameQuery.cpp | 85 ++- src/Interpreters/InterpreterSelectQuery.cpp | 60 +- .../InterpreterSelectWithUnionQuery.cpp | 10 +- .../InterpreterShowTablesQuery.cpp | 2 +- src/Interpreters/InterpreterSystemQuery.cpp | 21 +- .../InterpreterTransactionControlQuery.cpp | 6 +- src/Interpreters/InterpreterUndropQuery.cpp | 3 +- src/Interpreters/InterpreterWatchQuery.cpp | 2 +- src/Interpreters/JIT/CHJIT.cpp | 9 +- src/Interpreters/JoinUtils.cpp | 7 +- src/Interpreters/MergeJoin.cpp | 7 +- src/Interpreters/MergeTreeTransaction.cpp | 2 +- src/Interpreters/MutationsInterpreter.cpp | 5 +- .../MySQL/InterpretersMySQLDDLQuery.cpp | 10 +- ...OrDateTimeConverterWithPreimageVisitor.cpp | 48 +- src/Interpreters/OptimizeIfChains.cpp | 16 +- src/Interpreters/ProcessList.cpp | 5 +- .../RewriteArrayExistsFunctionVisitor.cpp | 3 +- ...writeSumFunctionWithSumAndCountVisitor.cpp | 16 +- .../RewriteUniqToCountVisitor.cpp | 33 +- src/Interpreters/Session.cpp | 16 +- src/Interpreters/Set.cpp | 20 +- src/Interpreters/StorageID.cpp | 3 +- src/Interpreters/TemporaryDataOnDisk.cpp | 7 +- src/Interpreters/TransactionLog.cpp | 2 +- src/Interpreters/TreeCNFConverter.cpp | 3 +- src/Interpreters/castColumn.cpp | 3 +- src/Interpreters/convertFieldToType.cpp | 109 ++-- .../evaluateConstantExpression.cpp | 9 +- src/Interpreters/executeDDLQueryOnCluster.cpp | 23 +- src/Interpreters/executeQuery.cpp | 4 +- src/Interpreters/inplaceBlockConversions.cpp | 2 +- src/Interpreters/loadMetadata.cpp | 16 +- .../replaceForPositionalArguments.cpp | 10 +- src/Parsers/ASTDropQuery.cpp | 7 +- src/Parsers/ASTIdentifier.cpp | 19 +- src/Parsers/ASTSampleRatio.cpp | 3 +- src/Parsers/ASTSelectQuery.cpp | 4 +- src/Parsers/ASTSelectWithUnionQuery.cpp | 16 +- src/Parsers/Access/ParserCreateQuotaQuery.cpp | 3 +- src/Parsers/Access/ParserGrantQuery.cpp | 10 +- src/Parsers/Access/ParserRowPolicyName.cpp | 10 +- .../Access/ParserSettingsProfileElement.cpp | 7 +- src/Parsers/ExpressionElementParsers.cpp | 37 +- src/Parsers/ExpressionListParsers.cpp | 79 ++- src/Parsers/FunctionSecretArgumentsFinder.h | 2 +- src/Parsers/IParser.h | 3 +- .../KustoFunctions/IParserKQLFunction.cpp | 4 +- .../KustoFunctions/KQLDataTypeFunctions.cpp | 16 +- .../KustoFunctions/KQLDynamicFunctions.cpp | 3 +- .../KustoFunctions/KQLStringFunctions.cpp | 5 +- src/Parsers/Kusto/ParserKQLQuery.cpp | 23 +- src/Parsers/Kusto/parseKQLQuery.cpp | 19 +- src/Parsers/Lexer.cpp | 61 +- src/Parsers/MySQL/ASTAlterCommand.cpp | 13 +- src/Parsers/MySQL/ASTDeclareOption.cpp | 13 +- src/Parsers/ParserCreateQuery.cpp | 30 +- src/Parsers/ParserDropQuery.cpp | 7 +- src/Parsers/ParserRenameQuery.cpp | 2 +- src/Parsers/ParserSetQuery.cpp | 4 +- src/Parsers/ParserUndropQuery.cpp | 3 +- src/Parsers/TokenIterator.cpp | 2 +- src/Parsers/parseDatabaseAndTableName.cpp | 2 +- src/Parsers/parseQuery.cpp | 16 +- src/Parsers/queryNormalization.cpp | 4 +- src/Planner/Planner.cpp | 28 +- src/Planner/PlannerActionsVisitor.cpp | 22 +- src/Planner/PlannerJoinTree.cpp | 7 +- src/Planner/PlannerJoins.cpp | 15 +- src/Planner/PlannerWindowFunctions.cpp | 10 +- src/Planner/Utils.cpp | 2 +- src/Processors/Executors/PipelineExecutor.cpp | 2 +- src/Processors/Formats/ISchemaReader.cpp | 17 +- src/Processors/Formats/ISchemaReader.h | 19 +- .../Formats/Impl/ArrowColumnToCHColumn.cpp | 22 +- .../Formats/Impl/AvroRowInputFormat.cpp | 50 +- .../Formats/Impl/AvroRowOutputFormat.cpp | 14 +- .../Impl/BSONEachRowRowInputFormat.cpp | 22 +- .../Formats/Impl/CSVRowInputFormat.cpp | 18 +- .../Impl/ConstantExpressionTemplate.cpp | 100 ++- .../Impl/JSONAsStringRowInputFormat.cpp | 2 +- .../Impl/JSONEachRowRowInputFormat.cpp | 24 +- .../Formats/Impl/JSONRowInputFormat.cpp | 8 +- .../Impl/LineAsStringRowInputFormat.cpp | 2 +- .../Impl/NativeORCBlockInputFormat.cpp | 38 +- .../Formats/Impl/NpyRowInputFormat.cpp | 17 +- .../Formats/Impl/ORCBlockInputFormat.cpp | 2 +- .../Impl/Parquet/ParquetLeafColReader.cpp | 5 +- .../Impl/Parquet/ParquetRecordReader.cpp | 8 +- src/Processors/Formats/Impl/Parquet/Write.cpp | 6 +- .../Formats/Impl/ParquetBlockInputFormat.cpp | 7 +- .../Formats/Impl/PrettyBlockOutputFormat.cpp | 10 +- .../Impl/PrometheusTextOutputFormat.cpp | 6 +- .../Formats/Impl/RegexpRowInputFormat.cpp | 2 +- .../Formats/Impl/TSKVRowInputFormat.cpp | 38 +- .../Impl/TabSeparatedRowInputFormat.cpp | 12 +- .../Impl/TemplateBlockOutputFormat.cpp | 21 +- .../Formats/Impl/ValuesBlockInputFormat.cpp | 14 +- src/Processors/Merges/Algorithms/Graphite.cpp | 20 +- .../GraphiteRollupSortedAlgorithm.cpp | 10 +- src/Processors/QueryPlan/DistinctStep.cpp | 44 +- .../Optimizations/mergeExpressions.cpp | 11 +- .../Optimizations/optimizeReadInOrder.cpp | 6 +- .../Optimizations/removeRedundantDistinct.cpp | 4 +- .../Optimizations/removeRedundantSorting.cpp | 2 +- src/Processors/QueryPlan/PartsSplitter.cpp | 2 +- .../QueryPlan/ReadFromMemoryStorageStep.cpp | 6 +- .../QueryPlan/ReadFromMergeTree.cpp | 14 +- src/Processors/QueryPlan/ReadFromRemote.cpp | 30 +- .../QueryPlan/ReadFromSystemNumbersStep.cpp | 14 +- .../Sources/MongoDBPocoLegacySource.cpp | 22 +- src/Processors/Sources/SQLiteSource.cpp | 11 +- src/Processors/Sources/ShellCommandSource.cpp | 8 +- src/Processors/Sources/SourceFromChunks.cpp | 3 +- src/Processors/TTL/ITTLAlgorithm.cpp | 6 +- .../Transforms/AddingDefaultsTransform.cpp | 2 +- .../AggregatingInOrderTransform.cpp | 38 +- .../Transforms/AggregatingTransform.cpp | 10 +- .../Transforms/CheckSortedTransform.cpp | 8 +- .../Transforms/ColumnGathererTransform.h | 2 +- .../Transforms/MergeJoinTransform.cpp | 18 +- .../Transforms/PartialSortingTransform.cpp | 2 +- .../Transforms/SortingTransform.cpp | 40 +- src/Processors/Transforms/WindowTransform.cpp | 25 +- .../getSourceFromASTInsertQuery.cpp | 3 +- src/QueryPipeline/QueryPipeline.cpp | 7 +- src/QueryPipeline/QueryPipelineBuilder.cpp | 8 +- src/QueryPipeline/RemoteInserter.cpp | 6 +- src/QueryPipeline/RemoteQueryExecutor.cpp | 3 +- src/Server/GRPCServer.cpp | 17 +- .../WriteBufferFromHTTPServerResponse.cpp | 40 +- src/Server/HTTP/exceptionCodeToHTTPStatus.cpp | 77 +-- src/Server/HTTPHandlerFactory.cpp | 14 +- src/Server/HTTPHandlerFactory.h | 2 +- src/Server/InterserverIOHTTPHandler.cpp | 2 +- src/Server/KeeperTCPHandler.cpp | 32 +- .../PrometheusRequestHandlerFactory.cpp | 11 +- src/Server/TCPHandler.cpp | 32 +- src/Storages/AlterCommands.cpp | 96 ++- src/Storages/Cache/RemoteCacheController.cpp | 3 +- .../DistributedAsyncInsertDirectoryQueue.cpp | 3 +- src/Storages/FileLog/FileLogConsumer.cpp | 14 +- .../FileLog/FileLogDirectoryWatcher.cpp | 8 +- src/Storages/FileLog/FileLogSource.cpp | 6 +- src/Storages/FileLog/StorageFileLog.cpp | 14 +- src/Storages/FileLog/StorageFileLog.h | 3 +- src/Storages/Hive/HiveCommon.cpp | 6 +- src/Storages/Hive/HiveFile.cpp | 20 +- src/Storages/Hive/StorageHive.cpp | 29 +- src/Storages/IStorage.cpp | 7 +- src/Storages/KVStorageUtils.cpp | 78 ++- src/Storages/Kafka/KafkaConsumer.cpp | 44 +- src/Storages/Kafka/KafkaConsumer2.cpp | 20 +- src/Storages/Kafka/KafkaSource.cpp | 17 +- src/Storages/Kafka/StorageKafka2.cpp | 20 +- src/Storages/Kafka/StorageKafkaUtils.cpp | 31 +- src/Storages/LiveView/LiveViewEventsSource.h | 10 +- src/Storages/LiveView/LiveViewSource.h | 10 +- src/Storages/LiveView/StorageLiveView.cpp | 2 +- src/Storages/MaterializedView/RefreshTask.cpp | 3 +- src/Storages/MergeTree/AllMergeSelector.cpp | 3 +- .../MergeTree/DataPartStorageOnDiskBase.cpp | 2 +- .../MergeTree/DataPartStorageOnDiskFull.cpp | 3 +- .../MergeTree/EphemeralLockInZooKeeper.cpp | 2 +- src/Storages/MergeTree/GinIndexStore.cpp | 26 +- src/Storages/MergeTree/IMergeTreeDataPart.cpp | 21 +- .../MergeTree/IMergeTreeDataPartWriter.cpp | 24 +- src/Storages/MergeTree/KeyCondition.cpp | 49 +- src/Storages/MergeTree/LeaderElection.h | 4 +- .../MergeTree/MergeFromLogEntryTask.cpp | 14 +- .../MergeTree/MergeProjectionPartsTask.cpp | 8 +- .../MergeTree/MergeTreeBlockReadUtils.cpp | 2 +- .../MergeTree/MergeTreeBlockReadUtils.h | 7 +- src/Storages/MergeTree/MergeTreeData.cpp | 222 ++++--- .../MergeTree/MergeTreeDataPartBuilder.cpp | 3 +- .../MergeTree/MergeTreeDataSelectExecutor.cpp | 43 +- .../MergeTree/MergeTreeIndexBloomFilter.cpp | 26 +- .../MergeTreeIndexBloomFilterText.cpp | 37 +- .../MergeTree/MergeTreeIndexFullText.cpp | 33 +- .../MergeTree/MergeTreeIndexGranularity.cpp | 3 +- .../MergeTreeIndexGranularityInfo.cpp | 5 +- .../MergeTree/MergeTreeIndexMinMax.cpp | 2 +- src/Storages/MergeTree/MergeTreeIndexSet.cpp | 24 +- .../MergeTreeIndexVectorSimilarity.cpp | 19 +- src/Storages/MergeTree/MergeTreeIndices.cpp | 6 +- .../MergeTree/MergeTreeMutationStatus.cpp | 2 +- src/Storages/MergeTree/MergeTreePartInfo.cpp | 3 +- .../MergeTree/MergeTreePartsMover.cpp | 3 +- .../MergeTree/MergeTreeRangeReader.cpp | 58 +- .../MergeTree/MergeTreeSelectProcessor.cpp | 6 +- .../MergeTree/MergeTreeWhereOptimizer.cpp | 4 +- .../MergeTree/MutateFromLogEntryTask.cpp | 14 +- src/Storages/MergeTree/MutateTask.cpp | 7 +- .../ParallelReplicasReadingCoordinator.cpp | 6 +- .../PartMovesBetweenShardsOrchestrator.cpp | 578 +++++++++--------- .../PartMovesBetweenShardsOrchestrator.h | 32 +- src/Storages/MergeTree/RPNBuilder.cpp | 100 ++- .../ReplicatedMergeTreeCleanupThread.cpp | 7 +- .../ReplicatedMergeTreePartCheckThread.cpp | 2 +- .../MergeTree/ReplicatedMergeTreeQueue.cpp | 25 +- .../MergeTree/ReplicatedMergeTreeSink.cpp | 28 +- .../MergeTree/VectorSimilarityCondition.cpp | 7 +- .../MergeTree/registerStorageMergeTree.cpp | 52 +- src/Storages/MutationCommands.cpp | 47 +- src/Storages/NATS/NATSSource.cpp | 6 +- src/Storages/NATS/StorageNATS.cpp | 16 +- src/Storages/NamedCollectionsHelpers.cpp | 2 +- .../ObjectStorage/Azure/Configuration.cpp | 18 +- .../DataLakes/DeltaLakeMetadata.cpp | 30 +- .../DataLakes/IStorageDataLake.h | 13 +- .../DataLakes/IcebergMetadata.cpp | 2 +- .../HDFS/AsynchronousReadBufferFromHDFS.cpp | 2 +- .../ObjectStorage/HDFS/HDFSCommon.cpp | 20 +- .../ObjectStorage/ReadBufferIterator.cpp | 3 +- .../ObjectStorage/StorageObjectStorage.cpp | 20 +- .../StorageObjectStorageCluster.cpp | 3 +- .../StorageObjectStorageSource.cpp | 22 +- .../ObjectStorageQueueMetadata.cpp | 5 +- .../ObjectStorageQueueOrderedFileMetadata.cpp | 6 +- .../ObjectStorageQueueSource.cpp | 77 ++- src/Storages/PartitionCommands.cpp | 23 +- src/Storages/RabbitMQ/RabbitMQSource.cpp | 8 +- src/Storages/RabbitMQ/StorageRabbitMQ.cpp | 12 +- src/Storages/RedisCommon.cpp | 2 +- src/Storages/SelectQueryDescription.cpp | 13 +- .../ConditionSelectivityEstimator.cpp | 16 +- src/Storages/StatisticsDescription.cpp | 2 +- src/Storages/StorageBuffer.cpp | 2 +- src/Storages/StorageDictionary.cpp | 35 +- src/Storages/StorageDistributed.cpp | 29 +- src/Storages/StorageExecutable.h | 3 +- src/Storages/StorageFactory.cpp | 30 +- src/Storages/StorageFile.cpp | 113 ++-- src/Storages/StorageFuzzJSON.cpp | 7 +- src/Storages/StorageKeeperMap.cpp | 6 +- src/Storages/StorageMaterializedView.cpp | 6 +- src/Storages/StorageMerge.cpp | 6 +- src/Storages/StorageMergeTree.cpp | 64 +- src/Storages/StorageRedis.cpp | 44 +- src/Storages/StorageReplicatedMergeTree.cpp | 348 ++++++----- src/Storages/StorageURL.cpp | 24 +- .../System/StorageSystemAsyncLoader.cpp | 3 +- .../System/StorageSystemPartsBase.cpp | 2 +- .../System/StorageSystemStackTrace.cpp | 3 +- .../PrometheusRemoteReadProtocol.cpp | 24 +- .../PrometheusRemoteWriteProtocol.cpp | 21 +- .../TimeSeriesDefinitionNormalizer.cpp | 30 +- src/Storages/Utils.cpp | 8 +- src/Storages/VirtualColumnUtils.cpp | 7 +- src/Storages/WindowView/StorageWindowView.cpp | 31 +- src/Storages/WindowView/WindowViewSource.h | 14 +- src/Storages/buildQueryTreeForShard.cpp | 16 +- src/Storages/extractKeyExpressionList.cpp | 15 +- .../transformQueryForExternalDatabase.cpp | 2 +- src/TableFunctions/ITableFunctionDataLake.h | 6 +- src/TableFunctions/TableFunctionFactory.cpp | 3 +- src/TableFunctions/TableFunctionFile.cpp | 3 +- src/TableFunctions/TableFunctionNumbers.cpp | 11 +- .../TableFunctionObjectStorage.cpp | 3 +- src/TableFunctions/TableFunctionRemote.cpp | 12 +- src/TableFunctions/TableFunctionZeros.cpp | 12 +- utils/keeper-data-dumper/main.cpp | 11 +- utils/zookeeper-dump-tree/main.cpp | 6 +- 802 files changed, 6604 insertions(+), 7807 deletions(-) diff --git a/.clang-tidy b/.clang-tidy index bb63bf2eea6..374abe0ad60 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -116,7 +116,6 @@ Checks: [ '-readability-avoid-unconditional-preprocessor-if', '-readability-braces-around-statements', '-readability-convert-member-functions-to-static', - '-readability-else-after-return', '-readability-function-cognitive-complexity', '-readability-function-size', '-readability-identifier-length', diff --git a/base/base/DecomposedFloat.h b/base/base/DecomposedFloat.h index 4837782621e..28dc3004240 100644 --- a/base/base/DecomposedFloat.h +++ b/base/base/DecomposedFloat.h @@ -110,8 +110,7 @@ struct DecomposedFloat { if (!isNegative()) return rhs > 0 ? -1 : 1; - else - return rhs >= 0 ? -1 : 1; + return rhs >= 0 ? -1 : 1; } /// The case of the most negative integer @@ -128,8 +127,7 @@ struct DecomposedFloat if (mantissa() == 0) return 0; - else - return -1; + return -1; } } @@ -169,9 +167,8 @@ struct DecomposedFloat /// Float has no fractional part means that the numbers are equal. if (large_and_always_integer || (mantissa() & ((1ULL << (Traits::mantissa_bits - normalizedExponent())) - 1)) == 0) return 0; - else - /// Float has fractional part means its abs value is larger. - return isNegative() ? -1 : 1; + /// Float has fractional part means its abs value is larger. + return isNegative() ? -1 : 1; } diff --git a/base/base/JSON.cpp b/base/base/JSON.cpp index a68b6663e50..5cc00518504 100644 --- a/base/base/JSON.cpp +++ b/base/base/JSON.cpp @@ -205,8 +205,7 @@ JSON::ElementType JSON::getType() const Pos after_string = skipString(); if (after_string < ptr_end && *after_string == ':') return TYPE_NAME_VALUE_PAIR; - else - return TYPE_STRING; + return TYPE_STRING; } default: throw JSONException(std::string("JSON: unexpected char ") + *ptr_begin + ", expected one of '{[tfn-0123456789\"'"); @@ -474,8 +473,7 @@ JSON::Pos JSON::searchField(const char * data, size_t size) const if (it == end()) return nullptr; - else - return it->data(); + return it->data(); } @@ -487,7 +485,7 @@ bool JSON::hasEscapes() const if (*pos == '"') return false; - else if (*pos == '\\') + if (*pos == '\\') return true; throw JSONException("JSON: unexpected end of data."); } @@ -503,7 +501,7 @@ bool JSON::hasSpecialChars() const if (*pos == '"') return false; - else if (pos < ptr_end) + if (pos < ptr_end) return true; throw JSONException("JSON: unexpected end of data."); } @@ -682,10 +680,9 @@ double JSON::toDouble() const if (type == TYPE_NUMBER) return getDouble(); - else if (type == TYPE_STRING) + if (type == TYPE_STRING) return JSON(ptr_begin + 1, ptr_end, level + 1).getDouble(); - else - throw JSONException("JSON: cannot convert value to double."); + throw JSONException("JSON: cannot convert value to double."); } Int64 JSON::toInt() const @@ -694,10 +691,9 @@ Int64 JSON::toInt() const if (type == TYPE_NUMBER) return getInt(); - else if (type == TYPE_STRING) + if (type == TYPE_STRING) return JSON(ptr_begin + 1, ptr_end, level + 1).getInt(); - else - throw JSONException("JSON: cannot convert value to signed integer."); + throw JSONException("JSON: cannot convert value to signed integer."); } UInt64 JSON::toUInt() const @@ -706,10 +702,9 @@ UInt64 JSON::toUInt() const if (type == TYPE_NUMBER) return getUInt(); - else if (type == TYPE_STRING) + if (type == TYPE_STRING) return JSON(ptr_begin + 1, ptr_end, level + 1).getUInt(); - else - throw JSONException("JSON: cannot convert value to unsigned integer."); + throw JSONException("JSON: cannot convert value to unsigned integer."); } std::string JSON::toString() const @@ -718,11 +713,9 @@ std::string JSON::toString() const if (type == TYPE_STRING) return getString(); - else - { - Pos pos = skipElement(); - return std::string(ptr_begin, pos - ptr_begin); - } + + Pos pos = skipElement(); + return std::string(ptr_begin, pos - ptr_begin); } diff --git a/base/base/JSON.h b/base/base/JSON.h index 7b9acf11d9a..03dd62d639d 100644 --- a/base/base/JSON.h +++ b/base/base/JSON.h @@ -203,9 +203,7 @@ T JSON::getWithDefault(const std::string & key, const T & default_) const if (key_json.isType()) return key_json.get(); - else - return default_; - } - else return default_; + } + return default_; } diff --git a/base/base/StringRef.h b/base/base/StringRef.h index fc0674b8440..af3441c2a75 100644 --- a/base/base/StringRef.h +++ b/base/base/StringRef.h @@ -151,19 +151,19 @@ inline bool memequalWide(const char * p1, const char * p2, size_t size) return unalignedLoad(p1) == unalignedLoad(p2) && unalignedLoad(p1 + size - 8) == unalignedLoad(p2 + size - 8); } - else if (size >= 4) + if (size >= 4) { /// Chunks of 4..7 bytes. return unalignedLoad(p1) == unalignedLoad(p2) && unalignedLoad(p1 + size - 4) == unalignedLoad(p2 + size - 4); } - else if (size >= 2) + if (size >= 2) { /// Chunks of 2..3 bytes. return unalignedLoad(p1) == unalignedLoad(p2) && unalignedLoad(p1 + size - 2) == unalignedLoad(p2 + size - 2); } - else if (size >= 1) + if (size >= 1) { /// A single byte. return *p1 == *p2; diff --git a/base/base/argsToConfig.cpp b/base/base/argsToConfig.cpp index faa1462218d..56ff1815d64 100644 --- a/base/base/argsToConfig.cpp +++ b/base/base/argsToConfig.cpp @@ -53,10 +53,9 @@ void argsToConfig(const Poco::Util::Application::ArgVec & argv, key = arg.substr(key_start); continue; } - else - { - key = ""; - } + + key = ""; + if (key_start == std::string::npos) continue; diff --git a/base/base/find_symbols.h b/base/base/find_symbols.h index 30ee759ba33..6d4c96f911c 100644 --- a/base/base/find_symbols.h +++ b/base/base/find_symbols.h @@ -330,9 +330,8 @@ inline const char * find_first_symbols_dispatch(const char * begin, const char * #if defined(__SSE4_2__) if (sizeof...(symbols) >= 5) return find_first_symbols_sse42(begin, end); - else #endif - return find_first_symbols_sse2(begin, end); + return find_first_symbols_sse2(begin, end); } template @@ -341,9 +340,8 @@ inline const char * find_first_symbols_dispatch(const std::string_view haystack, #if defined(__SSE4_2__) if (symbols.str.size() >= 5) return find_first_symbols_sse42(haystack.begin(), haystack.end(), symbols); - else #endif - return find_first_symbols_sse2(haystack.begin(), haystack.end(), symbols.str.data(), symbols.str.size()); + return find_first_symbols_sse2(haystack.begin(), haystack.end(), symbols.str.data(), symbols.str.size()); } } diff --git a/base/base/getMemoryAmount.cpp b/base/base/getMemoryAmount.cpp index bbfbecdbffd..4179e601e0f 100644 --- a/base/base/getMemoryAmount.cpp +++ b/base/base/getMemoryAmount.cpp @@ -33,8 +33,7 @@ std::optional getCgroupsV2MemoryLimit() uint64_t value; if (setting_file >> value) return {value}; - else - return {}; /// e.g. the cgroups default "max" + return {}; /// e.g. the cgroups default "max" } current_cgroup = current_cgroup.parent_path(); } diff --git a/programs/benchmark/Benchmark.cpp b/programs/benchmark/Benchmark.cpp index df1e090457a..eb60888df14 100644 --- a/programs/benchmark/Benchmark.cpp +++ b/programs/benchmark/Benchmark.cpp @@ -445,15 +445,13 @@ private: shutdown = true; throw; } - else - { - std::cerr << getCurrentExceptionMessage(print_stacktrace, - true /*check embedded stack trace*/) << std::endl; - size_t info_index = round_robin ? 0 : connection_index; - ++comparison_info_per_interval[info_index]->errors; - ++comparison_info_total[info_index]->errors; - } + std::cerr << getCurrentExceptionMessage(print_stacktrace, + true /*check embedded stack trace*/) << std::endl; + + size_t info_index = round_robin ? 0 : connection_index; + ++comparison_info_per_interval[info_index]->errors; + ++comparison_info_total[info_index]->errors; } // Count failed queries toward executed, so that we'd reach // max_iterations even if every run fails. diff --git a/programs/client/Client.cpp b/programs/client/Client.cpp index 1f99134aa10..60e70260850 100644 --- a/programs/client/Client.cpp +++ b/programs/client/Client.cpp @@ -480,27 +480,23 @@ void Client::connect() } catch (const Exception & e) { + /// This problem can't be fixed with reconnection so it is not attempted if (e.code() == DB::ErrorCodes::AUTHENTICATION_FAILED) - { - /// This problem can't be fixed with reconnection so it is not attempted throw; - } - else - { - if (attempted_address_index == hosts_and_ports.size() - 1) - throw; - if (is_interactive) - { - std::cerr << "Connection attempt to database at " - << connection_parameters.host << ":" << connection_parameters.port - << " resulted in failure" - << std::endl - << getExceptionMessage(e, false) - << std::endl - << "Attempting connection to the next provided address" - << std::endl; - } + if (attempted_address_index == hosts_and_ports.size() - 1) + throw; + + if (is_interactive) + { + std::cerr << "Connection attempt to database at " + << connection_parameters.host << ":" << connection_parameters.port + << " resulted in failure" + << std::endl + << getExceptionMessage(e, false) + << std::endl + << "Attempting connection to the next provided address" + << std::endl; } } } diff --git a/programs/disks/CommandCopy.cpp b/programs/disks/CommandCopy.cpp index e3051f2702c..2732e46b9b5 100644 --- a/programs/disks/CommandCopy.cpp +++ b/programs/disks/CommandCopy.cpp @@ -46,7 +46,7 @@ public: path_from, disk_from.getDisk()->getName()); } - else if (disk_from.getDisk()->isFile(path_from)) + if (disk_from.getDisk()->isFile(path_from)) { auto target_location = getTargetLocation(path_from, disk_to, path_to); if (!disk_to.getDisk()->exists(target_location) || disk_to.getDisk()->isFile(target_location)) @@ -77,7 +77,7 @@ public: { throw Exception(ErrorCodes::BAD_ARGUMENTS, "cannot overwrite non-directory {} with directory {}", path_to, target_location); } - else if (!disk_to.getDisk()->exists(target_location)) + if (!disk_to.getDisk()->exists(target_location)) { disk_to.getDisk()->createDirectory(target_location); } diff --git a/programs/disks/CommandList.cpp b/programs/disks/CommandList.cpp index 77479b1d217..00ac5c5143b 100644 --- a/programs/disks/CommandList.cpp +++ b/programs/disks/CommandList.cpp @@ -72,13 +72,9 @@ private: auto path = [&]() -> String { if (relative_path.ends_with("/")) - { return relative_path + file_name; - } - else - { - return relative_path + "/" + file_name; - } + + return relative_path + "/" + file_name; }(); if (disk.isDirectory(path)) { diff --git a/programs/disks/CommandMove.cpp b/programs/disks/CommandMove.cpp index e3d485032e0..cba8a3745cf 100644 --- a/programs/disks/CommandMove.cpp +++ b/programs/disks/CommandMove.cpp @@ -53,10 +53,8 @@ public: { throw Exception(ErrorCodes::BAD_ARGUMENTS, "cannot move '{}' to '{}': Directory not empty", path_from, target_location); } - else - { - disk.getDisk()->moveDirectory(path_from, target_location); - } + + disk.getDisk()->moveDirectory(path_from, target_location); } } else if (!disk.getDisk()->exists(path_from)) diff --git a/programs/disks/CommandRemove.cpp b/programs/disks/CommandRemove.cpp index 4388f6c0b14..c7e0cf22ab7 100644 --- a/programs/disks/CommandRemove.cpp +++ b/programs/disks/CommandRemove.cpp @@ -32,16 +32,14 @@ public: { throw Exception(ErrorCodes::BAD_ARGUMENTS, "Path {} on disk {} doesn't exist", path, disk.getDisk()->getName()); } - else if (disk.getDisk()->isDirectory(path)) + if (disk.getDisk()->isDirectory(path)) { if (!recursive) { throw Exception(ErrorCodes::BAD_ARGUMENTS, "cannot remove '{}': Is a directory", path); } - else - { - disk.getDisk()->removeRecursive(path); - } + + disk.getDisk()->removeRecursive(path); } else { diff --git a/programs/disks/CommandWrite.cpp b/programs/disks/CommandWrite.cpp index 0497281b3c4..547ebc11459 100644 --- a/programs/disks/CommandWrite.cpp +++ b/programs/disks/CommandWrite.cpp @@ -33,14 +33,10 @@ public: auto in = [&]() -> std::unique_ptr { if (!path_from.has_value()) - { return std::make_unique(STDIN_FILENO); - } - else - { - String relative_path_from = disk.getRelativeFromRoot(path_from.value()); - return disk.getDisk()->readFile(relative_path_from, getReadSettings()); - } + + String relative_path_from = disk.getRelativeFromRoot(path_from.value()); + return disk.getDisk()->readFile(relative_path_from, getReadSettings()); }(); auto out = disk.getDisk()->writeFile(path_to); diff --git a/programs/disks/DisksApp.cpp b/programs/disks/DisksApp.cpp index 884550ff2ed..5fddfce0678 100644 --- a/programs/disks/DisksApp.cpp +++ b/programs/disks/DisksApp.cpp @@ -127,68 +127,58 @@ std::vector DisksApp::getCompletions(const String & prefix) const } return getEmptyCompletion(command->command_name); } - else if (arguments.size() == 1) + if (arguments.size() == 1) { String command_prefix = arguments[0]; return getCommandsToComplete(command_prefix); } - else - { - String last_token = arguments.back(); - CommandPtr command; - try - { - command = getCommandByName(arguments[0]); - } - catch (...) - { - return {last_token}; - } - std::vector answer = {}; - if (command->command_name == "help") - { - return getCommandsToComplete(last_token); - } - else - { - answer = [&]() -> std::vector - { - if (multidisk_commands.contains(command->command_name)) - { - return client->getAllFilesByPatternFromAllDisks(last_token); - } - else - { - return client->getCurrentDiskWithPath().getAllFilesByPattern(last_token); - } - }(); - for (const auto & disk_name : client->getAllDiskNames()) - { - if (disk_name.starts_with(last_token)) - { - answer.push_back(disk_name); - } - } - for (const auto & option : command->options_description.options()) - { - String option_sign = "--" + option->long_name(); - if (option_sign.starts_with(last_token)) - { - answer.push_back(option_sign); - } - } - } - if (!answer.empty()) + String last_token = arguments.back(); + CommandPtr command; + try + { + command = getCommandByName(arguments[0]); + } + catch (...) + { + return {last_token}; + } + + std::vector answer = {}; + if (command->command_name == "help") + return getCommandsToComplete(last_token); + + answer = [&]() -> std::vector + { + if (multidisk_commands.contains(command->command_name)) + return client->getAllFilesByPatternFromAllDisks(last_token); + + return client->getCurrentDiskWithPath().getAllFilesByPattern(last_token); + }(); + + for (const auto & disk_name : client->getAllDiskNames()) + { + if (disk_name.starts_with(last_token)) { - std::sort(answer.begin(), answer.end()); - return answer; - } - else - { - return {last_token}; + answer.push_back(disk_name); } } + for (const auto & option : command->options_description.options()) + { + String option_sign = "--" + option->long_name(); + if (option_sign.starts_with(last_token)) + { + answer.push_back(option_sign); + } + } + + if (!answer.empty()) + { + std::sort(answer.begin(), answer.end()); + return answer; + } + + return {last_token}; } bool DisksApp::processQueryText(const String & text) @@ -210,11 +200,11 @@ bool DisksApp::processQueryText(const String & text) catch (DB::Exception & err) { int code = getCurrentExceptionCode(); + if (code == ErrorCodes::LOGICAL_ERROR) - { throw std::move(err); - } - else if (code == ErrorCodes::BAD_ARGUMENTS) + + if (code == ErrorCodes::BAD_ARGUMENTS) { std::cerr << err.message() << "\n" << "\n"; diff --git a/programs/disks/DisksClient.cpp b/programs/disks/DisksClient.cpp index 53d7c7f78f6..af7fa1bf41f 100644 --- a/programs/disks/DisksClient.cpp +++ b/programs/disks/DisksClient.cpp @@ -49,10 +49,8 @@ std::vector DiskWithPath::listAllFilesByPath(const String & any_path) co disk->listFiles(getRelativeFromRoot(any_path), file_names); return file_names; } - else - { - return {}; - } + + return {}; } std::vector DiskWithPath::getAllFilesByPattern(const String & pattern) const @@ -61,39 +59,30 @@ std::vector DiskWithPath::getAllFilesByPattern(const String & pattern) c { auto slash_pos = pattern.find_last_of('/'); if (slash_pos >= pattern.size()) - { return {"", pattern}; - } - else - { - return {pattern.substr(0, slash_pos + 1), pattern.substr(slash_pos + 1, pattern.size() - slash_pos - 1)}; - } + + return {pattern.substr(0, slash_pos + 1), pattern.substr(slash_pos + 1, pattern.size() - slash_pos - 1)}; }(); if (!isDirectory(path_before)) - { return {}; - } - else + + std::vector file_names = listAllFilesByPath(path_before); + std::vector answer; + + for (const auto & file_name : file_names) { - std::vector file_names = listAllFilesByPath(path_before); - - std::vector answer; - - for (const auto & file_name : file_names) + if (file_name.starts_with(path_after)) { - if (file_name.starts_with(path_after)) + String file_pattern = path_before + file_name; + if (isDirectory(file_pattern)) { - String file_pattern = path_before + file_name; - if (isDirectory(file_pattern)) - { - file_pattern = file_pattern + "/"; - } - answer.push_back(file_pattern); + file_pattern = file_pattern + "/"; } + answer.push_back(file_pattern); } - return answer; } + return answer; }; void DiskWithPath::setPath(const String & any_path) diff --git a/programs/disks/ICommand.cpp b/programs/disks/ICommand.cpp index f622bcad3c6..3dd5c5c660c 100644 --- a/programs/disks/ICommand.cpp +++ b/programs/disks/ICommand.cpp @@ -39,13 +39,9 @@ DiskWithPath & ICommand::getDiskWithPath(DisksClient & client, const CommandLine { auto disk_name = getValueFromCommandLineOptionsWithOptional(options, name); if (disk_name.has_value()) - { return client.getDiskWithPath(disk_name.value()); - } - else - { - return client.getCurrentDiskWithPath(); - } + + return client.getCurrentDiskWithPath(); } } diff --git a/programs/disks/ICommand.h b/programs/disks/ICommand.h index 6faf90e2b52..46eda86c2f9 100644 --- a/programs/disks/ICommand.h +++ b/programs/disks/ICommand.h @@ -63,39 +63,27 @@ protected: static T getValueFromCommandLineOptionsThrow(const CommandLineOptions & options, const String & name) { if (options.count(name)) - { return getValueFromCommandLineOptions(options, name); - } - else - { - throw DB::Exception(ErrorCodes::BAD_ARGUMENTS, "Mandatory argument '{}' is missing", name); - } + + throw DB::Exception(ErrorCodes::BAD_ARGUMENTS, "Mandatory argument '{}' is missing", name); } template static T getValueFromCommandLineOptionsWithDefault(const CommandLineOptions & options, const String & name, const T & default_value) { if (options.count(name)) - { return getValueFromCommandLineOptions(options, name); - } - else - { - return default_value; - } + + return default_value; } template static std::optional getValueFromCommandLineOptionsWithOptional(const CommandLineOptions & options, const String & name) { if (options.count(name)) - { return std::optional{getValueFromCommandLineOptions(options, name)}; - } - else - { - return std::nullopt; - } + + return std::nullopt; } DiskWithPath & getDiskWithPath(DisksClient & client, const CommandLineOptions & options, const String & name); diff --git a/programs/install/Install.cpp b/programs/install/Install.cpp index d6576927a20..4029d3203b0 100644 --- a/programs/install/Install.cpp +++ b/programs/install/Install.cpp @@ -110,8 +110,8 @@ static auto executeScript(const std::string & command, bool throw_on_error = fal sh->wait(); return 0; } - else - return sh->tryWait(); + + return sh->tryWait(); } static bool ask(std::string question) diff --git a/programs/library-bridge/CatBoostLibraryHandlerFactory.cpp b/programs/library-bridge/CatBoostLibraryHandlerFactory.cpp index 7ce896636e7..c8dc1dc84c4 100644 --- a/programs/library-bridge/CatBoostLibraryHandlerFactory.cpp +++ b/programs/library-bridge/CatBoostLibraryHandlerFactory.cpp @@ -26,17 +26,15 @@ CatBoostLibraryHandlerPtr CatBoostLibraryHandlerFactory::tryGetModel(const Strin if (found) return handler->second; - else + + if (create_if_not_found) { - if (create_if_not_found) - { - auto new_handler = std::make_shared(library_path, model_path); - library_handlers.emplace(model_path, new_handler); - LOG_DEBUG(log, "Loaded catboost library handler for model path '{}'", model_path); - return new_handler; - } - return nullptr; + auto new_handler = std::make_shared(library_path, model_path); + library_handlers.emplace(model_path, new_handler); + LOG_DEBUG(log, "Loaded catboost library handler for model path '{}'", model_path); + return new_handler; } + return nullptr; } void CatBoostLibraryHandlerFactory::removeModel(const String & model_path) diff --git a/programs/library-bridge/LibraryBridgeHandlerFactory.cpp b/programs/library-bridge/LibraryBridgeHandlerFactory.cpp index 234904c6265..39b89ac01fa 100644 --- a/programs/library-bridge/LibraryBridgeHandlerFactory.cpp +++ b/programs/library-bridge/LibraryBridgeHandlerFactory.cpp @@ -25,7 +25,7 @@ std::unique_ptr LibraryBridgeHandlerFactory::createRequestHa { if (uri.getPath() == "/extdict_ping") return std::make_unique(getContext()); - else if (uri.getPath() == "/catboost_ping") + if (uri.getPath() == "/catboost_ping") return std::make_unique(getContext()); } @@ -33,7 +33,7 @@ std::unique_ptr LibraryBridgeHandlerFactory::createRequestHa { if (uri.getPath() == "/extdict_request") return std::make_unique(getContext()); - else if (uri.getPath() == "/catboost_request") + if (uri.getPath() == "/catboost_request") return std::make_unique(getContext()); } diff --git a/programs/library-bridge/LibraryBridgeHandlers.cpp b/programs/library-bridge/LibraryBridgeHandlers.cpp index 236256dc36b..c89562a62de 100644 --- a/programs/library-bridge/LibraryBridgeHandlers.cpp +++ b/programs/library-bridge/LibraryBridgeHandlers.cpp @@ -158,11 +158,9 @@ void ExternalDictionaryLibraryBridgeRequestHandler::handleRequest(HTTPServerRequ out.finalize(); return; } - else - { - LOG_TRACE(log, "Cannot clone from dictionary with id: {}, will call extDict_libNew instead", from_dictionary_id); - lib_new = true; - } + + LOG_TRACE(log, "Cannot clone from dictionary with id: {}, will call extDict_libNew instead", from_dictionary_id); + lib_new = true; } if (lib_new) { diff --git a/programs/obfuscator/Obfuscator.cpp b/programs/obfuscator/Obfuscator.cpp index 4c3981c1d01..324a4573b24 100644 --- a/programs/obfuscator/Obfuscator.cpp +++ b/programs/obfuscator/Obfuscator.cpp @@ -231,8 +231,8 @@ static Int64 transformSigned(Int64 x, UInt64 seed) { if (x >= 0) return transform(x, seed); - else - return -transform(-x, seed); /// It works Ok even for minimum signed number. + + return -transform(-x, seed); /// It works Ok even for minimum signed number. } @@ -1105,8 +1105,8 @@ public: { if (isUInt(data_type)) return std::make_unique(seed); - else - return std::make_unique(seed); + + return std::make_unique(seed); } if (typeid_cast(&data_type)) diff --git a/programs/odbc-bridge/getIdentifierQuote.cpp b/programs/odbc-bridge/getIdentifierQuote.cpp index e96da91ecb9..4bf19015cbb 100644 --- a/programs/odbc-bridge/getIdentifierQuote.cpp +++ b/programs/odbc-bridge/getIdentifierQuote.cpp @@ -39,13 +39,13 @@ IdentifierQuotingStyle getQuotingStyle(nanodbc::ConnectionHolderPtr connection) auto identifier_quote = getIdentifierQuote(connection); if (identifier_quote.empty()) return IdentifierQuotingStyle::Backticks; - else if (identifier_quote[0] == '`') + if (identifier_quote[0] == '`') return IdentifierQuotingStyle::Backticks; - else if (identifier_quote[0] == '"') + if (identifier_quote[0] == '"') return IdentifierQuotingStyle::DoubleQuotes; - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Can not map quote identifier '{}' to IdentifierQuotingStyle value", identifier_quote); + + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Can not map quote identifier '{}' to IdentifierQuotingStyle value", identifier_quote); } } diff --git a/programs/odbc-bridge/validateODBCConnectionString.cpp b/programs/odbc-bridge/validateODBCConnectionString.cpp index 72c3c9bddca..0133ba4732b 100644 --- a/programs/odbc-bridge/validateODBCConnectionString.cpp +++ b/programs/odbc-bridge/validateODBCConnectionString.cpp @@ -127,8 +127,8 @@ std::string validateODBCConnectionString(const std::string & connection_string) if (*pos == '{') return read_escaped_value(); - else - return read_plain_value(); + + return read_plain_value(); }; std::map parameters; @@ -206,12 +206,10 @@ std::string validateODBCConnectionString(const std::string & connection_string) reconstructed_connection_string.append(value_pos, next_pos - value_pos); break; } - else - { - reconstructed_connection_string.append(value_pos, next_pos - value_pos); - reconstructed_connection_string.append("}}"); - value_pos = next_pos + 1; - } + + reconstructed_connection_string.append(value_pos, next_pos - value_pos); + reconstructed_connection_string.append("}}"); + value_pos = next_pos + 1; } reconstructed_connection_string += '}'; diff --git a/src/Access/AccessBackup.cpp b/src/Access/AccessBackup.cpp index a24f8c5b2ad..3dee4447e8c 100644 --- a/src/Access/AccessBackup.cpp +++ b/src/Access/AccessBackup.cpp @@ -116,16 +116,14 @@ namespace reading_dependents = false; continue; } - else if (line == "DEPENDENTS") + if (line == "DEPENDENTS") { reading_dependents = true; reading_dependencies = false; continue; } - else if (line.empty()) - { + if (line.empty()) continue; - } size_t separator1 = line.find('\t'); size_t separator2 = line.find('\t', separator1 + 1); diff --git a/src/Access/AccessControl.cpp b/src/Access/AccessControl.cpp index 86f814bf5c7..1b397304a06 100644 --- a/src/Access/AccessControl.cpp +++ b/src/Access/AccessControl.cpp @@ -134,8 +134,8 @@ public: "' registered for user-defined settings", String{setting_name}, boost::algorithm::join(registered_prefixes, "' or '")); } - else - throw Exception(ErrorCodes::UNKNOWN_SETTING, "Unknown setting '{}'", String{setting_name}); + + throw Exception(ErrorCodes::UNKNOWN_SETTING, "Unknown setting '{}'", String{setting_name}); } private: @@ -830,8 +830,7 @@ std::shared_ptr AccessControl::getAuthenticationQuota( quota_key, throw_if_client_key_empty); } - else - return nullptr; + return nullptr; } diff --git a/src/Access/AccessRights.cpp b/src/Access/AccessRights.cpp index ccaec79526b..49a8505fccf 100644 --- a/src/Access/AccessRights.cpp +++ b/src/Access/AccessRights.cpp @@ -1483,17 +1483,17 @@ bool AccessRights::isGrantedImplHelper(const AccessRightsElement & element) cons { if (element.anyParameter()) return isGrantedImpl(element.access_flags); - else - return isGrantedImpl(element.access_flags, element.parameter); + + return isGrantedImpl(element.access_flags, element.parameter); } - else if (element.anyDatabase()) + if (element.anyDatabase()) return isGrantedImpl(element.access_flags); - else if (element.anyTable()) + if (element.anyTable()) return isGrantedImpl(element.access_flags, element.database); - else if (element.anyColumn()) + if (element.anyColumn()) return isGrantedImpl(element.access_flags, element.database, element.table); - else - return isGrantedImpl(element.access_flags, element.database, element.table, element.columns); + + return isGrantedImpl(element.access_flags, element.database, element.table, element.columns); } template @@ -1503,16 +1503,14 @@ bool AccessRights::isGrantedImpl(const AccessRightsElement & element) const { if (element.grant_option) return isGrantedImplHelper(element); - else - return isGrantedImplHelper(element); - } - else - { - if (element.grant_option) - return isGrantedImplHelper(element); - else - return isGrantedImplHelper(element); + + return isGrantedImplHelper(element); } + + if (element.grant_option) + return isGrantedImplHelper(element); + + return isGrantedImplHelper(element); } template diff --git a/src/Access/AuthenticationData.cpp b/src/Access/AuthenticationData.cpp index 97010e67c5e..92bf2145909 100644 --- a/src/Access/AuthenticationData.cpp +++ b/src/Access/AuthenticationData.cpp @@ -501,10 +501,9 @@ AuthenticationData AuthenticationData::fromAST(const ASTAuthenticationData & que auth_data.setPasswordHashBinary(AuthenticationData::Util::stringToDigest(value)); return auth_data; } - else - { - auth_data.setPasswordHashHex(value); - } + + auth_data.setPasswordHashHex(value); + if (query.type == AuthenticationType::SHA256_PASSWORD && args_size == 2) { diff --git a/src/Access/Common/AccessFlags.cpp b/src/Access/Common/AccessFlags.cpp index 23c52d86f4e..8d1d5bf10f0 100644 --- a/src/Access/Common/AccessFlags.cpp +++ b/src/Access/Common/AccessFlags.cpp @@ -247,8 +247,7 @@ namespace const auto & unused_node = *(owned_nodes.begin()->second); if (unused_node.node_type == UNKNOWN) throw Exception(ErrorCodes::LOGICAL_ERROR, "Parent group '{}' not found", unused_node.keyword); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Access type '{}' should have parent group", unused_node.keyword); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Access type '{}' should have parent group", unused_node.keyword); } } diff --git a/src/Access/Common/AllowedClientHosts.cpp b/src/Access/Common/AllowedClientHosts.cpp index 2875f65579e..8d766b47c08 100644 --- a/src/Access/Common/AllowedClientHosts.cpp +++ b/src/Access/Common/AllowedClientHosts.cpp @@ -61,7 +61,7 @@ namespace { if (addr.family() == IPAddress::Family::IPv4 && addr_v6 == toIPv6(addr)) return true; - else if (addr.family() == IPAddress::Family::IPv6 && addr_v6 == addr) + if (addr.family() == IPAddress::Family::IPv6 && addr_v6 == addr) return true; } @@ -267,10 +267,9 @@ String AllowedClientHosts::IPSubnet::toString() const unsigned int prefix_length = mask.prefixLength(); if (isMaskAllBitsOne()) return prefix.toString(); - else if (IPAddress{prefix_length, mask.family()} == mask) + if (IPAddress{prefix_length, mask.family()} == mask) return fs::path(prefix.toString()) / std::to_string(prefix_length); - else - return fs::path(prefix.toString()) / mask.toString(); + return fs::path(prefix.toString()) / mask.toString(); } bool AllowedClientHosts::IPSubnet::isMaskAllBitsOne() const @@ -575,12 +574,11 @@ bool AllowedClientHosts::contains(const IPAddress & client_address) const parseLikePattern(pattern, subnet, name, name_regexp); if (subnet) return check_subnet(*subnet); - else if (name) + if (name) return check_name(*name); - else if (name_regexp) + if (name_regexp) return check_name_regexp(*name_regexp); - else - return false; + return false; }; for (const String & like_pattern : like_patterns) diff --git a/src/Access/Common/QuotaDefs.cpp b/src/Access/Common/QuotaDefs.cpp index 2a22b80f65d..eb60446e214 100644 --- a/src/Access/Common/QuotaDefs.cpp +++ b/src/Access/Common/QuotaDefs.cpp @@ -28,16 +28,14 @@ String QuotaTypeInfo::valueToString(QuotaValue value) const { if (!(value % output_denominator)) return std::to_string(value / output_denominator); - else - return toString(static_cast(value) / output_denominator); + return toString(static_cast(value) / output_denominator); } QuotaValue QuotaTypeInfo::stringToValue(const String & str) const { if (output_denominator == 1) return static_cast(parse(str)); - else - return static_cast(parse(str) * output_denominator); + return static_cast(parse(str) * output_denominator); } String QuotaTypeInfo::valueToStringWithName(QuotaValue value) const diff --git a/src/Access/ContextAccess.cpp b/src/Access/ContextAccess.cpp index 23090294a76..e3bc14b5612 100644 --- a/src/Access/ContextAccess.cpp +++ b/src/Access/ContextAccess.cpp @@ -728,8 +728,7 @@ bool ContextAccess::checkAccessImplHelper(const ContextPtr & context, AccessFlag "For queries over HTTP, method GET implies readonly. " "You should use method POST for modifying queries"); } - else - return access_denied(ErrorCodes::READONLY, "{}: Cannot execute query in readonly mode"); + return access_denied(ErrorCodes::READONLY, "{}: Cannot execute query in readonly mode"); } } @@ -770,17 +769,17 @@ bool ContextAccess::checkAccessImplHelper(const ContextPtr & context, const Acce { if (element.anyParameter()) return checkAccessImpl(context, element.access_flags); - else - return checkAccessImpl(context, element.access_flags, element.parameter); + + return checkAccessImpl(context, element.access_flags, element.parameter); } - else if (element.anyDatabase()) + if (element.anyDatabase()) return checkAccessImpl(context, element.access_flags); - else if (element.anyTable()) + if (element.anyTable()) return checkAccessImpl(context, element.access_flags, element.database); - else if (element.anyColumn()) + if (element.anyColumn()) return checkAccessImpl(context, element.access_flags, element.database, element.table); - else - return checkAccessImpl(context, element.access_flags, element.database, element.table, element.columns); + + return checkAccessImpl(context, element.access_flags, element.database, element.table, element.columns); } template @@ -790,16 +789,14 @@ bool ContextAccess::checkAccessImpl(const ContextPtr & context, const AccessRigh { if (element.grant_option) return checkAccessImplHelper(context, element); - else - return checkAccessImplHelper(context, element); - } - else - { - if (element.grant_option) - return checkAccessImplHelper(context, element); - else - return checkAccessImplHelper(context, element); + + return checkAccessImplHelper(context, element); } + + if (element.grant_option) + return checkAccessImplHelper(context, element); + + return checkAccessImplHelper(context, element); } template diff --git a/src/Access/ContextAccessParams.cpp b/src/Access/ContextAccessParams.cpp index fba6eaf9f03..f5a405c7bc1 100644 --- a/src/Access/ContextAccessParams.cpp +++ b/src/Access/ContextAccessParams.cpp @@ -89,10 +89,9 @@ bool operator ==(const ContextAccessParams & left, const ContextAccessParams & r { if (!x) return !y; - else if (!y) + if (!y) return false; - else - return *x == *y; + return *x == *y; } else { @@ -132,23 +131,21 @@ bool operator <(const ContextAccessParams & left, const ContextAccessParams & ri { if (!x) return y ? -1 : 0; - else if (!y) + if (!y) return 1; - else if (*x == *y) + if (*x == *y) return 0; - else if (*x < *y) + if (*x < *y) return -1; - else - return 1; + return 1; } else { if (x == y) return 0; - else if (x < y) + if (x < y) return -1; - else - return 1; + return 1; } }; diff --git a/src/Access/KerberosInit.cpp b/src/Access/KerberosInit.cpp index 3cda1c8e13c..e28a1d41fe0 100644 --- a/src/Access/KerberosInit.cpp +++ b/src/Access/KerberosInit.cpp @@ -166,8 +166,7 @@ void KerberosInit::init(const String & keytab_file, const String & principal, co ret = krb5_get_init_creds_keytab(k5.ctx, &my_creds, k5.me, keytab, 0, nullptr, options); if (ret) throw Exception(ErrorCodes::KERBEROS_ERROR, "Error in getting initial credentials: {}", fmtError(ret)); - else - LOG_TRACE(log,"Got initial credentials"); + LOG_TRACE(log, "Got initial credentials"); } else { diff --git a/src/Access/LDAPAccessStorage.cpp b/src/Access/LDAPAccessStorage.cpp index 4fbe0242bd7..2636a3cffbb 100644 --- a/src/Access/LDAPAccessStorage.cpp +++ b/src/Access/LDAPAccessStorage.cpp @@ -330,10 +330,7 @@ std::set LDAPAccessStorage::mapExternalRolesNoLock(const LDAPClient::Sea for (const auto & external_role : external_role_set) { - if ( - prefix.size() < external_role.size() && - external_role.compare(0, prefix.size(), prefix) == 0 - ) + if (prefix.size() < external_role.size() && external_role.starts_with(prefix)) { role_names.emplace(external_role, prefix.size()); } diff --git a/src/Access/QuotaCache.cpp b/src/Access/QuotaCache.cpp index dc49e9680ad..660a97bd80c 100644 --- a/src/Access/QuotaCache.cpp +++ b/src/Access/QuotaCache.cpp @@ -62,8 +62,7 @@ String QuotaCache::QuotaInfo::calculateKey(const EnabledQuota & enabled, bool th "Quota {} (for user {}) requires a client supplied key.", quota->getName(), params.user_name); - else - return ""; // Authentication quota has no client key at time of authentication. + return ""; // Authentication quota has no client key at time of authentication. } case QuotaKeyType::CLIENT_KEY_OR_USER_NAME: { diff --git a/src/Access/RolesOrUsersSet.cpp b/src/Access/RolesOrUsersSet.cpp index 3568b60e44d..3664ea41d5d 100644 --- a/src/Access/RolesOrUsersSet.cpp +++ b/src/Access/RolesOrUsersSet.cpp @@ -80,15 +80,13 @@ void RolesOrUsersSet::init(const ASTRolesOrUsersSet & ast, const AccessControl * return *id; return access_control->getID(name); } - else if (ast.allow_users) + if (ast.allow_users) { return access_control->getID(name); } - else - { - assert(ast.allow_roles); - return access_control->getID(name); - } + + assert(ast.allow_roles); + return access_control->getID(name); }; if (!ast.names.empty() && !all) diff --git a/src/Access/SettingsAuthResponseParser.cpp b/src/Access/SettingsAuthResponseParser.cpp index a90ae61f93a..b82d60e1c66 100644 --- a/src/Access/SettingsAuthResponseParser.cpp +++ b/src/Access/SettingsAuthResponseParser.cpp @@ -28,7 +28,7 @@ SettingsAuthResponseParser::parse(const Poco::Net::HTTPResponse & response, std: try { Poco::Dynamic::Var json = parser.parse(*body_stream); - Poco::JSON::Object::Ptr obj = json.extract(); + const Poco::JSON::Object::Ptr & obj = json.extract(); Poco::JSON::Object::Ptr settings_obj = obj->getObject(settings_key); if (settings_obj) diff --git a/src/Access/SettingsConstraints.cpp b/src/Access/SettingsConstraints.cpp index ecf7537f6a9..4305568dd8b 100644 --- a/src/Access/SettingsConstraints.cpp +++ b/src/Access/SettingsConstraints.cpp @@ -54,8 +54,7 @@ SettingSourceRestrictions getSettingSourceRestrictions(std::string_view name) auto settingConstraintIter = SETTINGS_SOURCE_RESTRICTIONS.find(name); if (settingConstraintIter != SETTINGS_SOURCE_RESTRICTIONS.end()) return settingConstraintIter->second; - else - return SettingSourceRestrictions(); // allows everything + return SettingSourceRestrictions(); // allows everything } } @@ -310,8 +309,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, { if (reaction == THROW_ON_VIOLATION) throw Exception(explain, code); - else - return false; + return false; } std::string_view setting_name = setting_name_resolver(change.name); @@ -335,8 +333,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, { if (reaction == THROW_ON_VIOLATION) throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} should not be changed", setting_name); - else - return false; + return false; } const auto & min_value = constraint.min_value; @@ -351,8 +348,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, max_value, min_value, setting_name); - else - return false; + return false; } if (!min_value.isNull() && less_or_cannot_compare(new_value, min_value)) @@ -362,8 +358,7 @@ bool SettingsConstraints::Checker::check(SettingChange & change, throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} shouldn't be less than {}", setting_name, applyVisitor(FieldVisitorToString(), min_value)); } - else - change.value = min_value; + change.value = min_value; } if (!max_value.isNull() && less_or_cannot_compare(max_value, new_value)) @@ -373,16 +368,14 @@ bool SettingsConstraints::Checker::check(SettingChange & change, throw Exception(ErrorCodes::SETTING_CONSTRAINT_VIOLATION, "Setting {} shouldn't be greater than {}", setting_name, applyVisitor(FieldVisitorToString(), max_value)); } - else - change.value = max_value; + change.value = max_value; } if (!getSettingSourceRestrictions(setting_name).isSourceAllowed(source)) { if (reaction == THROW_ON_VIOLATION) throw Exception(ErrorCodes::READONLY, "Setting {} is not allowed to be set by {}", setting_name, toString(source)); - else - return false; + return false; } return true; diff --git a/src/Access/UsersConfigAccessStorage.cpp b/src/Access/UsersConfigAccessStorage.cpp index a723511b800..b89d5f136b3 100644 --- a/src/Access/UsersConfigAccessStorage.cpp +++ b/src/Access/UsersConfigAccessStorage.cpp @@ -649,8 +649,7 @@ namespace { if (users_without_row_policies_can_read_rows) continue; - else - filter = "1"; + filter = "1"; } auto policy = std::make_shared(); diff --git a/src/AggregateFunctions/AggregateFunctionAnyRespectNulls.cpp b/src/AggregateFunctions/AggregateFunctionAnyRespectNulls.cpp index 0b6642bffac..cce4f26d813 100644 --- a/src/AggregateFunctions/AggregateFunctionAnyRespectNulls.cpp +++ b/src/AggregateFunctions/AggregateFunctionAnyRespectNulls.cpp @@ -157,13 +157,13 @@ public: d.status = static_cast(k); if (d.status == Data::Status::NotSet) return; - else if (d.status == Data::Status::SetNull) + if (d.status == Data::Status::SetNull) { if (!returns_nullable_type) throw Exception(ErrorCodes::INCORRECT_DATA, "Incorrect type (NULL) in non-nullable {}State", getName()); return; } - else if (d.status == Data::Status::SetOther) + if (d.status == Data::Status::SetOther) { serialization->deserializeBinary(d.value, buf, {}); return; diff --git a/src/AggregateFunctions/AggregateFunctionDeltaSum.cpp b/src/AggregateFunctions/AggregateFunctionDeltaSum.cpp index a846490a89e..42169c34c25 100644 --- a/src/AggregateFunctions/AggregateFunctionDeltaSum.cpp +++ b/src/AggregateFunctions/AggregateFunctionDeltaSum.cpp @@ -148,9 +148,8 @@ AggregateFunctionPtr createAggregateFunctionDeltaSum( if (isInteger(data_type) || isFloat(data_type)) return AggregateFunctionPtr(createWithNumericType( *data_type, arguments, params)); - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of argument for aggregate function {}", - arguments[0]->getName(), name); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of argument for aggregate function {}", arguments[0]->getName(), name); } } diff --git a/src/AggregateFunctions/AggregateFunctionFactory.cpp b/src/AggregateFunctions/AggregateFunctionFactory.cpp index bf2a4b18afd..ac969f2ebfd 100644 --- a/src/AggregateFunctions/AggregateFunctionFactory.cpp +++ b/src/AggregateFunctions/AggregateFunctionFactory.cpp @@ -137,13 +137,12 @@ AggregateFunctionFactory::getAssociatedFunctionByNullsAction(const String & name { if (action == NullsAction::RESPECT_NULLS) { - if (auto it = respect_nulls.find(name); it == respect_nulls.end()) + auto it = respect_nulls.find(name); + if (it == respect_nulls.end()) throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Function {} does not support RESPECT NULLS", name); - else if (auto associated_it = aggregate_functions.find(it->second); associated_it != aggregate_functions.end()) + if (auto associated_it = aggregate_functions.find(it->second); associated_it != aggregate_functions.end()) return {associated_it->second}; - else - throw Exception( - ErrorCodes::LOGICAL_ERROR, "Unable to find the function {} (equivalent to '{} RESPECT NULLS')", it->second, name); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unable to find the function {} (equivalent to '{} RESPECT NULLS')", it->second, name); } if (action == NullsAction::IGNORE_NULLS) @@ -152,9 +151,8 @@ AggregateFunctionFactory::getAssociatedFunctionByNullsAction(const String & name { if (auto associated_it = aggregate_functions.find(it->second); associated_it != aggregate_functions.end()) return {associated_it->second}; - else - throw Exception( - ErrorCodes::LOGICAL_ERROR, "Unable to find the function {} (equivalent to '{} IGNORE NULLS')", it->second, name); + throw Exception( + ErrorCodes::LOGICAL_ERROR, "Unable to find the function {} (equivalent to '{} IGNORE NULLS')", it->second, name); } /// We don't throw for IGNORE NULLS of other functions because that's the default in CH } @@ -263,8 +261,7 @@ AggregateFunctionPtr AggregateFunctionFactory::getImpl( if (!hints.empty()) throw Exception(ErrorCodes::UNKNOWN_AGGREGATE_FUNCTION, "Unknown aggregate function {}{}. Maybe you meant: {}", name, extra_info, toString(hints)); - else - throw Exception(ErrorCodes::UNKNOWN_AGGREGATE_FUNCTION, "Unknown aggregate function {}{}", name, extra_info); + throw Exception(ErrorCodes::UNKNOWN_AGGREGATE_FUNCTION, "Unknown aggregate function {}{}", name, extra_info); } std::optional AggregateFunctionFactory::tryGetProperties(String name, NullsAction action) const diff --git a/src/AggregateFunctions/AggregateFunctionFlameGraph.cpp b/src/AggregateFunctions/AggregateFunctionFlameGraph.cpp index 7fc7251497f..a0b5b798a45 100644 --- a/src/AggregateFunctions/AggregateFunctionFlameGraph.cpp +++ b/src/AggregateFunctions/AggregateFunctionFlameGraph.cpp @@ -328,21 +328,19 @@ struct AggregateFunctionFlameGraphData list = list->next; return entry; } - else + + Entry * parent = list; + while (parent->next && parent->next->size != size) + parent = parent->next; + + if (parent->next && parent->next->size == size) { - Entry * parent = list; - while (parent->next && parent->next->size != size) - parent = parent->next; - - if (parent->next && parent->next->size == size) - { - Entry * entry = parent->next; - parent->next = entry->next; - return entry; - } - - return nullptr; + Entry * entry = parent->next; + parent->next = entry->next; + return entry; } + + return nullptr; } void add(UInt64 ptr, Int64 size, const UInt64 * stack, size_t stack_size, Arena * arena) diff --git a/src/AggregateFunctions/AggregateFunctionGroupArray.cpp b/src/AggregateFunctions/AggregateFunctionGroupArray.cpp index 5cc9f725b46..73db8091382 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupArray.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupArray.cpp @@ -90,8 +90,7 @@ struct GroupArraySamplerData /// With a large number of values, we will generate random numbers several times slower. if (lim <= static_cast(pcg32_fast::max())) return rng() % lim; - else - return (static_cast(rng()) * (static_cast(pcg32::max()) + 1ULL) + static_cast(rng())) % lim; + return (static_cast(rng()) * (static_cast(pcg32::max()) + 1ULL) + static_cast(rng())) % lim; } void randomShuffle() @@ -797,8 +796,8 @@ AggregateFunctionPtr createAggregateFunctionGroupArray( throw Exception(ErrorCodes::BAD_ARGUMENTS, "groupArrayLast make sense only with max_elems (groupArrayLast(max_elems)())"); return createAggregateFunctionGroupArrayImpl>(argument_types[0], parameters, max_elems, std::nullopt); } - else - return createAggregateFunctionGroupArrayImpl>(argument_types[0], parameters, max_elems, std::nullopt); + return createAggregateFunctionGroupArrayImpl>( + argument_types[0], parameters, max_elems, std::nullopt); } AggregateFunctionPtr createAggregateFunctionGroupArraySample( diff --git a/src/AggregateFunctions/AggregateFunctionGroupArrayIntersect.cpp b/src/AggregateFunctions/AggregateFunctionGroupArrayIntersect.cpp index 36d00b1d9ec..c7656a98de7 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupArrayIntersect.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupArrayIntersect.cpp @@ -381,23 +381,22 @@ IAggregateFunction * createWithExtraTypes(const DataTypePtr & argument_type, con { WhichDataType which(argument_type); if (which.idx == TypeIndex::Date) return new AggregateFunctionGroupArrayIntersectDate(argument_type, parameters); - else if (which.idx == TypeIndex::DateTime) return new AggregateFunctionGroupArrayIntersectDateTime(argument_type, parameters); - else if (which.idx == TypeIndex::Date32) return new AggregateFunctionGroupArrayIntersectDate32(argument_type, parameters); - else if (which.idx == TypeIndex::DateTime64) + if (which.idx == TypeIndex::DateTime) + return new AggregateFunctionGroupArrayIntersectDateTime(argument_type, parameters); + if (which.idx == TypeIndex::Date32) + return new AggregateFunctionGroupArrayIntersectDate32(argument_type, parameters); + if (which.idx == TypeIndex::DateTime64) { const auto * datetime64_type = dynamic_cast(argument_type.get()); const auto return_type = std::make_shared(std::make_shared(datetime64_type->getScale())); return new AggregateFunctionGroupArrayIntersectGeneric(argument_type, parameters, return_type); } - else - { - /// Check that we can use plain version of AggregateFunctionGroupArrayIntersectGeneric - if (argument_type->isValueUnambiguouslyRepresentedInContiguousMemoryRegion()) - return new AggregateFunctionGroupArrayIntersectGeneric(argument_type, parameters); - else - return new AggregateFunctionGroupArrayIntersectGeneric(argument_type, parameters); - } + + /// Check that we can use plain version of AggregateFunctionGroupArrayIntersectGeneric + if (argument_type->isValueUnambiguouslyRepresentedInContiguousMemoryRegion()) + return new AggregateFunctionGroupArrayIntersectGeneric(argument_type, parameters); + return new AggregateFunctionGroupArrayIntersectGeneric(argument_type, parameters); } inline AggregateFunctionPtr createAggregateFunctionGroupArrayIntersectImpl(const std::string & name, const DataTypePtr & argument_type, const Array & parameters) diff --git a/src/AggregateFunctions/AggregateFunctionGroupArrayMoving.cpp b/src/AggregateFunctions/AggregateFunctionGroupArrayMoving.cpp index 2c3ac7f883e..43aad8ac3ba 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupArrayMoving.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupArrayMoving.cpp @@ -65,8 +65,7 @@ struct MovingSumData : public MovingData { if (idx < window_size) return this->value[idx]; - else - return this->value[idx] - this->value[idx - window_size]; + return this->value[idx] - this->value[idx - window_size]; } }; @@ -79,8 +78,7 @@ struct MovingAvgData : public MovingData { if (idx < window_size) return this->value[idx] / T(window_size); - else - return (this->value[idx] - this->value[idx - window_size]) / T(window_size); + return (this->value[idx] - this->value[idx - window_size]) / T(window_size); } }; @@ -285,16 +283,12 @@ AggregateFunctionPtr createAggregateFunctionMoving( { if (isDecimal(argument_type)) return createAggregateFunctionMovingImpl(name, argument_type); - else - return createAggregateFunctionMovingImpl(name, argument_type); - } - else - { - if (isDecimal(argument_type)) - return createAggregateFunctionMovingImpl(name, argument_type, max_elems); - else - return createAggregateFunctionMovingImpl(name, argument_type, max_elems); + return createAggregateFunctionMovingImpl(name, argument_type); } + + if (isDecimal(argument_type)) + return createAggregateFunctionMovingImpl(name, argument_type, max_elems); + return createAggregateFunctionMovingImpl(name, argument_type, max_elems); } } diff --git a/src/AggregateFunctions/AggregateFunctionGroupArraySorted.cpp b/src/AggregateFunctions/AggregateFunctionGroupArraySorted.cpp index 27043ed6aa6..86f7661e53f 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupArraySorted.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupArraySorted.cpp @@ -391,21 +391,20 @@ AggregateFunctionPtr createAggregateFunctionGroupArray( { throw Exception(ErrorCodes::BAD_ARGUMENTS, "Parameter for aggregate function {} should have limit argument", name); } - else if (parameters.size() == 1) + if (parameters.size() == 1) { auto type = parameters[0].getType(); if (type != Field::Types::Int64 && type != Field::Types::UInt64) - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Parameter for aggregate function {} should be positive number", name); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Parameter for aggregate function {} should be positive number", name); - if ((type == Field::Types::Int64 && parameters[0].safeGet() < 0) || - (type == Field::Types::UInt64 && parameters[0].safeGet() == 0)) + if ((type == Field::Types::Int64 && parameters[0].safeGet() < 0) + || (type == Field::Types::UInt64 && parameters[0].safeGet() == 0)) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Parameter for aggregate function {} should be positive number", name); max_elems = parameters[0].safeGet(); } else - throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, - "Function {} does not support this number of arguments", name); + throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "Function {} does not support this number of arguments", name); if (max_elems > group_array_sorted_sort_strategy_max_elements_threshold) return createAggregateFunctionGroupArraySortedImpl(argument_types[0], parameters, max_elems); diff --git a/src/AggregateFunctions/AggregateFunctionGroupBitmap.cpp b/src/AggregateFunctions/AggregateFunctionGroupBitmap.cpp index 0cc5874f65e..540b739149b 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupBitmap.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupBitmap.cpp @@ -133,8 +133,7 @@ public: { if (revision >= STATE_VERSION_1_MIN_REVISION) return 1; - else - return 0; + return 0; } void serialize(ConstAggregateDataPtr __restrict place, WriteBuffer & buf, std::optional version) const override diff --git a/src/AggregateFunctions/AggregateFunctionGroupBitmapData.h b/src/AggregateFunctions/AggregateFunctionGroupBitmapData.h index c4676026d3f..4f09d61638a 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupBitmapData.h +++ b/src/AggregateFunctions/AggregateFunctionGroupBitmapData.h @@ -88,8 +88,7 @@ public: { if (isSmall()) return small.size(); - else - return roaring_bitmap->cardinality(); + return roaring_bitmap->cardinality(); } void merge(const RoaringBitmapWithSmallSet & r1) @@ -454,8 +453,7 @@ public: if (isSmall()) return small.find(static_cast(x)) != small.end(); - else - return roaring_bitmap->contains(static_cast(x)); + return roaring_bitmap->contains(static_cast(x)); } /** @@ -554,24 +552,22 @@ public: r1.add(elem); return answer.size(); } - else - { - UInt64 count = 0; - for (auto it = roaring_bitmap->begin(); it != roaring_bitmap->end(); ++it) - { - if (*it < range_start) - continue; - if (count < limit) - { - r1.add(*it); - ++count; - } - else - break; + UInt64 count = 0; + for (auto it = roaring_bitmap->begin(); it != roaring_bitmap->end(); ++it) + { + if (*it < range_start) + continue; + + if (count < limit) + { + r1.add(*it); + ++count; } - return count; + else + break; } + return count; } UInt64 rb_offset_limit(UInt64 offset, UInt64 limit, RoaringBitmapWithSmallSet & r1) const /// NOLINT @@ -591,18 +587,16 @@ public: r1.add(it->getValue()); return count; } - else - { - UInt64 count = 0; - UInt64 offset_count = 0; - auto it = roaring_bitmap->begin(); - for (;it != roaring_bitmap->end() && offset_count < offset; ++it) - ++offset_count; - for (;it != roaring_bitmap->end() && count < limit; ++it, ++count) - r1.add(*it); - return count; - } + UInt64 count = 0; + UInt64 offset_count = 0; + auto it = roaring_bitmap->begin(); + for (; it != roaring_bitmap->end() && offset_count < offset; ++it) + ++offset_count; + + for (; it != roaring_bitmap->end() && count < limit; ++it, ++count) + r1.add(*it); + return count; } UInt64 rb_min() const /// NOLINT @@ -620,8 +614,7 @@ public: } return min_val; } - else - return roaring_bitmap->minimum(); + return roaring_bitmap->minimum(); } UInt64 rb_max() const /// NOLINT @@ -639,8 +632,7 @@ public: } return max_val; } - else - return roaring_bitmap->maximum(); + return roaring_bitmap->maximum(); } /** diff --git a/src/AggregateFunctions/AggregateFunctionGroupConcat.cpp b/src/AggregateFunctions/AggregateFunctionGroupConcat.cpp index 8fb0b645096..8cf5ec5705a 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupConcat.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupConcat.cpp @@ -275,8 +275,7 @@ AggregateFunctionPtr createAggregateFunctionGroupConcat( if (has_limit) return std::make_shared>(argument_types[0], parameters, limit, delimiter); - else - return std::make_shared>(argument_types[0], parameters, limit, delimiter); + return std::make_shared>(argument_types[0], parameters, limit, delimiter); } } diff --git a/src/AggregateFunctions/AggregateFunctionGroupUniqArray.cpp b/src/AggregateFunctions/AggregateFunctionGroupUniqArray.cpp index 5cbf449c946..88edbc4a0ae 100644 --- a/src/AggregateFunctions/AggregateFunctionGroupUniqArray.cpp +++ b/src/AggregateFunctions/AggregateFunctionGroupUniqArray.cpp @@ -276,16 +276,15 @@ IAggregateFunction * createWithExtraTypes(const DataTypePtr & argument_type, TAr { WhichDataType which(argument_type); if (which.idx == TypeIndex::Date) return new AggregateFunctionGroupUniqArrayDate(argument_type, args...); - else if (which.idx == TypeIndex::DateTime) return new AggregateFunctionGroupUniqArrayDateTime(argument_type, args...); - else if (which.idx == TypeIndex::IPv4) return new AggregateFunctionGroupUniqArrayIPv4(argument_type, args...); - else - { - /// Check that we can use plain version of AggregateFunctionGroupUniqArrayGeneric - if (argument_type->isValueUnambiguouslyRepresentedInContiguousMemoryRegion()) - return new AggregateFunctionGroupUniqArrayGeneric(argument_type, args...); - else - return new AggregateFunctionGroupUniqArrayGeneric(argument_type, args...); - } + if (which.idx == TypeIndex::DateTime) + return new AggregateFunctionGroupUniqArrayDateTime(argument_type, args...); + if (which.idx == TypeIndex::IPv4) + return new AggregateFunctionGroupUniqArrayIPv4(argument_type, args...); + + /// Check that we can use plain version of AggregateFunctionGroupUniqArrayGeneric + if (argument_type->isValueUnambiguouslyRepresentedInContiguousMemoryRegion()) + return new AggregateFunctionGroupUniqArrayGeneric(argument_type, args...); + return new AggregateFunctionGroupUniqArrayGeneric(argument_type, args...); } template @@ -336,8 +335,7 @@ AggregateFunctionPtr createAggregateFunctionGroupUniqArray( if (!limit_size) return createAggregateFunctionGroupUniqArrayImpl(name, argument_types[0], parameters); - else - return createAggregateFunctionGroupUniqArrayImpl(name, argument_types[0], parameters, max_elems); + return createAggregateFunctionGroupUniqArrayImpl(name, argument_types[0], parameters, max_elems); } } diff --git a/src/AggregateFunctions/AggregateFunctionMaxIntersections.cpp b/src/AggregateFunctions/AggregateFunctionMaxIntersections.cpp index 6c26065a918..ca91f960dab 100644 --- a/src/AggregateFunctions/AggregateFunctionMaxIntersections.cpp +++ b/src/AggregateFunctions/AggregateFunctionMaxIntersections.cpp @@ -87,8 +87,7 @@ public: { if (kind_ == AggregateFunctionIntersectionsKind::Count) return std::make_shared(); - else - return std::make_shared>(); + return std::make_shared>(); } /// MaxIntersectionsData::Allocator uses the arena diff --git a/src/AggregateFunctions/AggregateFunctionQuantileGK.cpp b/src/AggregateFunctions/AggregateFunctionQuantileGK.cpp index e455f2f4123..f047f701eec 100644 --- a/src/AggregateFunctions/AggregateFunctionQuantileGK.cpp +++ b/src/AggregateFunctions/AggregateFunctionQuantileGK.cpp @@ -138,7 +138,9 @@ public: { if (other.count == 0) return; - else if (count == 0) + + /// NOLINTBEGIN(readability-else-after-return) + if (count == 0) { compress_threshold = other.compress_threshold; relative_error = other.relative_error; @@ -237,6 +239,7 @@ public: doCompress(2 * merged_relative_error * merged_count); compressed = true; } + /// NOLINTEND(readability-else-after-return) } void write(WriteBuffer & buf) const @@ -292,12 +295,10 @@ private: Int64 max_rank = min_rank + curr_sample.delta; if (max_rank - target_error <= rank && rank <= min_rank + target_error) return {i, min_rank, curr_sample.value}; - else - { - ++i; - curr_sample = sampled[i]; - min_rank += curr_sample.g; - } + + ++i; + curr_sample = sampled[i]; + min_rank += curr_sample.g; } return {sampled.size() - 1, 0, sampled.back().value}; } diff --git a/src/AggregateFunctions/AggregateFunctionSequenceMatch.cpp b/src/AggregateFunctions/AggregateFunctionSequenceMatch.cpp index 5b542a7d904..bac83c21e44 100644 --- a/src/AggregateFunctions/AggregateFunctionSequenceMatch.cpp +++ b/src/AggregateFunctions/AggregateFunctionSequenceMatch.cpp @@ -747,7 +747,7 @@ AggregateFunctionPtr createAggregateFunctionSequenceBase( WhichDataType which(argument_types.front().get()); if (which.isDateTime()) return std::make_shared>>(argument_types, params, pattern); - else if (which.isDate()) + if (which.isDate()) return std::make_shared>>(argument_types, params, pattern); throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, diff --git a/src/AggregateFunctions/AggregateFunctionStatistics.cpp b/src/AggregateFunctions/AggregateFunctionStatistics.cpp index e128e06557e..1d522477b01 100644 --- a/src/AggregateFunctions/AggregateFunctionStatistics.cpp +++ b/src/AggregateFunctions/AggregateFunctionStatistics.cpp @@ -124,8 +124,7 @@ private: { if (count < 2) return std::numeric_limits::infinity(); - else - return m2 / (count - 1); + return m2 / (count - 1); } static Float64 getStddevSamp(Float64 m2, UInt64 count) @@ -137,10 +136,9 @@ private: { if (count == 0) return std::numeric_limits::infinity(); - else if (count == 1) + if (count == 1) return 0.0; - else - return m2 / count; + return m2 / count; } static Float64 getStddevPop(Float64 m2, UInt64 count) @@ -363,26 +361,23 @@ private: { if (count < 2) return std::numeric_limits::infinity(); - else - return co_moment / (count - 1); + return co_moment / (count - 1); } static Float64 getCovarPop(Float64 co_moment, UInt64 count) { if (count == 0) return std::numeric_limits::infinity(); - else if (count == 1) + if (count == 1) return 0.0; - else - return co_moment / count; + return co_moment / count; } static Float64 getCorr(Float64 co_moment, Float64 left_m2, Float64 right_m2, UInt64 count) { if (count < 2) return std::numeric_limits::infinity(); - else - return co_moment / sqrt(left_m2 * right_m2); + return co_moment / sqrt(left_m2 * right_m2); } Float64 getResult(ConstAggregateDataPtr __restrict place) const diff --git a/src/AggregateFunctions/AggregateFunctionSumMap.cpp b/src/AggregateFunctions/AggregateFunctionSumMap.cpp index 55db0a43a6e..0441bb538d7 100644 --- a/src/AggregateFunctions/AggregateFunctionSumMap.cpp +++ b/src/AggregateFunctions/AggregateFunctionSumMap.cpp @@ -112,8 +112,7 @@ public: { if (revision >= STATE_VERSION_1_MIN_REVISION) return 1; - else - return 0; + return 0; } static DataTypePtr createResultType( @@ -764,8 +763,7 @@ void registerAggregateFunctionSumMap(AggregateFunctionFactory & factory) auto [keys_type, values_types, tuple_argument] = parseArguments(name, arguments); if (tuple_argument) return std::make_shared>(keys_type, values_types, arguments, params); - else - return std::make_shared>(keys_type, values_types, arguments, params); + return std::make_shared>(keys_type, values_types, arguments, params); }); factory.registerFunction("minMappedArrays", [](const std::string & name, const DataTypes & arguments, const Array & params, const Settings *) -> AggregateFunctionPtr @@ -773,8 +771,7 @@ void registerAggregateFunctionSumMap(AggregateFunctionFactory & factory) auto [keys_type, values_types, tuple_argument] = parseArguments(name, arguments); if (tuple_argument) return std::make_shared>(keys_type, values_types, arguments, params); - else - return std::make_shared>(keys_type, values_types, arguments, params); + return std::make_shared>(keys_type, values_types, arguments, params); }); factory.registerFunction("maxMappedArrays", [](const std::string & name, const DataTypes & arguments, const Array & params, const Settings *) -> AggregateFunctionPtr @@ -782,8 +779,7 @@ void registerAggregateFunctionSumMap(AggregateFunctionFactory & factory) auto [keys_type, values_types, tuple_argument] = parseArguments(name, arguments); if (tuple_argument) return std::make_shared>(keys_type, values_types, arguments, params); - else - return std::make_shared>(keys_type, values_types, arguments, params); + return std::make_shared>(keys_type, values_types, arguments, params); }); // these functions could be renamed to *MappedArrays too, but it would @@ -793,8 +789,7 @@ void registerAggregateFunctionSumMap(AggregateFunctionFactory & factory) auto [keys_type, values_types, tuple_argument] = parseArguments(name, arguments); if (tuple_argument) return std::make_shared>(keys_type, values_types, arguments, params); - else - return std::make_shared>(keys_type, values_types, arguments, params); + return std::make_shared>(keys_type, values_types, arguments, params); }); factory.registerFunction("sumMapFiltered", [](const std::string & name, const DataTypes & arguments, const Array & params, const Settings *) -> AggregateFunctionPtr @@ -802,8 +797,7 @@ void registerAggregateFunctionSumMap(AggregateFunctionFactory & factory) auto [keys_type, values_types, tuple_argument] = parseArguments(name, arguments); if (tuple_argument) return std::make_shared>(keys_type, values_types, arguments, params); - else - return std::make_shared>(keys_type, values_types, arguments, params); + return std::make_shared>(keys_type, values_types, arguments, params); }); factory.registerFunction("sumMapFilteredWithOverflow", [](const std::string & name, const DataTypes & arguments, const Array & params, const Settings *) -> AggregateFunctionPtr @@ -811,8 +805,7 @@ void registerAggregateFunctionSumMap(AggregateFunctionFactory & factory) auto [keys_type, values_types, tuple_argument] = parseArguments(name, arguments); if (tuple_argument) return std::make_shared>(keys_type, values_types, arguments, params); - else - return std::make_shared>(keys_type, values_types, arguments, params); + return std::make_shared>(keys_type, values_types, arguments, params); }); } diff --git a/src/AggregateFunctions/AggregateFunctionTTest.h b/src/AggregateFunctions/AggregateFunctionTTest.h index 749e711d4f7..45407b83206 100644 --- a/src/AggregateFunctions/AggregateFunctionTTest.h +++ b/src/AggregateFunctions/AggregateFunctionTTest.h @@ -96,25 +96,18 @@ public: std::move(names) ); } - else - { - DataTypes types - { - std::make_shared>(), - std::make_shared>(), - }; - Strings names - { - "t_statistic", - "p_value", - }; + DataTypes types{ + std::make_shared>(), + std::make_shared>(), + }; - return std::make_shared( - std::move(types), - std::move(names) - ); - } + Strings names{ + "t_statistic", + "p_value", + }; + + return std::make_shared(std::move(types), std::move(names)); } bool allocatesMemoryInArena() const override { return false; } diff --git a/src/AggregateFunctions/AggregateFunctionTopK.cpp b/src/AggregateFunctions/AggregateFunctionTopK.cpp index f949f6b7e4a..26108054e87 100644 --- a/src/AggregateFunctions/AggregateFunctionTopK.cpp +++ b/src/AggregateFunctions/AggregateFunctionTopK.cpp @@ -79,8 +79,7 @@ public: { if (is_approx_top_k) return is_weighted ? "approx_top_sum" : "approx_top_k"; - else - return is_weighted ? "topKWeighted" : "topK"; + return is_weighted ? "topKWeighted" : "topK"; } static DataTypePtr createResultType(const DataTypes & argument_types_, bool include_counts_) @@ -106,8 +105,7 @@ public: std::move(names) )); } - else - return std::make_shared(argument_types_[0]); + return std::make_shared(argument_types_[0]); } bool allocatesMemoryInArena() const override { return false; } @@ -226,8 +224,7 @@ public: { if (is_approx_top_k) return is_weighted ? "approx_top_sum" : "approx_top_k"; - else - return is_weighted ? "topKWeighted" : "topK"; + return is_weighted ? "topKWeighted" : "topK"; } static DataTypePtr createResultType(const DataTypes & argument_types_, bool include_counts_) @@ -253,10 +250,8 @@ public: std::move(names) )); - } else - { - return std::make_shared(argument_types_[0]); } + return std::make_shared(argument_types_[0]); } bool allocatesMemoryInArena() const override @@ -440,8 +435,8 @@ IAggregateFunction * createWithExtraTypes(const DataTypes & argument_types, UInt /// Check that we can use plain version of AggregateFunctionTopKGeneric if (argument_types[0]->isValueUnambiguouslyRepresentedInContiguousMemoryRegion()) return new AggregateFunctionTopKGeneric(threshold, reserved, include_counts, is_approx_top_k, argument_types, params); - else - return new AggregateFunctionTopKGeneric(threshold, reserved, include_counts, is_approx_top_k, argument_types, params); + return new AggregateFunctionTopKGeneric( + threshold, reserved, include_counts, is_approx_top_k, argument_types, params); } diff --git a/src/AggregateFunctions/AggregateFunctionUniq.cpp b/src/AggregateFunctions/AggregateFunctionUniq.cpp index e5eec16fa49..07f0a11d269 100644 --- a/src/AggregateFunctions/AggregateFunctionUniq.cpp +++ b/src/AggregateFunctions/AggregateFunctionUniq.cpp @@ -54,34 +54,32 @@ createAggregateFunctionUniq(const std::string & name, const DataTypes & argument WhichDataType which(argument_type); if (res) return res; - else if (which.isDate()) + if (which.isDate()) return std::make_shared>(argument_types); - else if (which.isDate32()) + if (which.isDate32()) return std::make_shared>(argument_types); - else if (which.isDateTime()) + if (which.isDateTime()) return std::make_shared>(argument_types); - else if (which.isStringOrFixedString()) + if (which.isStringOrFixedString()) return std::make_shared>(argument_types); - else if (which.isUUID()) + if (which.isUUID()) return std::make_shared>(argument_types); - else if (which.isIPv4()) + if (which.isIPv4()) return std::make_shared>(argument_types); - else if (which.isIPv6()) + if (which.isIPv6()) return std::make_shared>(argument_types); - else if (which.isTuple()) + if (which.isTuple()) { if (use_exact_hash_function) return std::make_shared>>(argument_types); - else - return std::make_shared>>(argument_types); + return std::make_shared>>(argument_types); } } /// "Variadic" method also works as a fallback generic case for single argument. if (use_exact_hash_function) return std::make_shared>>(argument_types); - else - return std::make_shared>>(argument_types); + return std::make_shared>>(argument_types); } template typename Data, template typename DataForVariadic, bool is_able_to_parallelize_merge> @@ -107,34 +105,46 @@ createAggregateFunctionUniq(const std::string & name, const DataTypes & argument WhichDataType which(argument_type); if (res) return res; - else if (which.isDate()) - return std::make_shared>>(argument_types); - else if (which.isDate32()) - return std::make_shared>>(argument_types); - else if (which.isDateTime()) - return std::make_shared>>(argument_types); - else if (which.isStringOrFixedString()) + if (which.isDate()) + return std::make_shared< + AggregateFunctionUniq>>( + argument_types); + if (which.isDate32()) + return std::make_shared< + AggregateFunctionUniq>>( + argument_types); + if (which.isDateTime()) + return std::make_shared< + AggregateFunctionUniq>>( + argument_types); + if (which.isStringOrFixedString()) return std::make_shared>>(argument_types); - else if (which.isUUID()) - return std::make_shared>>(argument_types); - else if (which.isIPv4()) - return std::make_shared>>(argument_types); - else if (which.isIPv6()) - return std::make_shared>>(argument_types); - else if (which.isTuple()) + if (which.isUUID()) + return std::make_shared< + AggregateFunctionUniq>>( + argument_types); + if (which.isIPv4()) + return std::make_shared< + AggregateFunctionUniq>>( + argument_types); + if (which.isIPv6()) + return std::make_shared< + AggregateFunctionUniq>>( + argument_types); + if (which.isTuple()) { if (use_exact_hash_function) - return std::make_shared>>(argument_types); - else - return std::make_shared>>(argument_types); + return std::make_shared>>( + argument_types); + return std::make_shared>>( + argument_types); } } /// "Variadic" method also works as a fallback generic case for single argument. if (use_exact_hash_function) return std::make_shared>>(argument_types); - else - return std::make_shared>>(argument_types); + return std::make_shared>>(argument_types); } } @@ -155,9 +165,11 @@ void registerAggregateFunctionsUniq(AggregateFunctionFactory & factory) if (settings && (*settings)[Setting::max_threads] > 1) return createAggregateFunctionUniq< true, AggregateFunctionUniqExactData, AggregateFunctionUniqExactDataForVariadic, true /* is_able_to_parallelize_merge */>(name, argument_types, params, settings); - else - return createAggregateFunctionUniq< - true, AggregateFunctionUniqExactData, AggregateFunctionUniqExactDataForVariadic, false /* is_able_to_parallelize_merge */>(name, argument_types, params, settings); + return createAggregateFunctionUniq< + true, + AggregateFunctionUniqExactData, + AggregateFunctionUniqExactDataForVariadic, + false /* is_able_to_parallelize_merge */>(name, argument_types, params, settings); }; factory.registerFunction("uniqExact", {assign_bool_param, properties}); diff --git a/src/AggregateFunctions/AggregateFunctionUniqCombined.h b/src/AggregateFunctions/AggregateFunctionUniqCombined.h index 6d5486a3b09..c6377a9532d 100644 --- a/src/AggregateFunctions/AggregateFunctionUniqCombined.h +++ b/src/AggregateFunctions/AggregateFunctionUniqCombined.h @@ -235,34 +235,40 @@ AggregateFunctionPtr createAggregateFunctionWithK(const DataTypes & argument_typ WhichDataType which(argument_type); if (res) return res; - else if (which.isDate()) - return std::make_shared::template AggregateFunction>(argument_types, params); - else if (which.isDate32()) - return std::make_shared::template AggregateFunction>(argument_types, params); - else if (which.isDateTime()) - return std::make_shared::template AggregateFunction>(argument_types, params); - else if (which.isStringOrFixedString()) + if (which.isDate()) + return std::make_shared::template AggregateFunction>( + argument_types, params); + if (which.isDate32()) + return std::make_shared::template AggregateFunction>( + argument_types, params); + if (which.isDateTime()) + return std::make_shared::template AggregateFunction>( + argument_types, params); + if (which.isStringOrFixedString()) return std::make_shared::template AggregateFunction>(argument_types, params); - else if (which.isUUID()) - return std::make_shared::template AggregateFunction>(argument_types, params); - else if (which.isIPv4()) - return std::make_shared::template AggregateFunction>(argument_types, params); - else if (which.isIPv6()) - return std::make_shared::template AggregateFunction>(argument_types, params); - else if (which.isTuple()) + if (which.isUUID()) + return std::make_shared::template AggregateFunction>( + argument_types, params); + if (which.isIPv4()) + return std::make_shared::template AggregateFunction>( + argument_types, params); + if (which.isIPv6()) + return std::make_shared::template AggregateFunction>( + argument_types, params); + if (which.isTuple()) { if (use_exact_hash_function) - return std::make_shared::template AggregateFunctionVariadic>(argument_types, params); - else - return std::make_shared::template AggregateFunctionVariadic>(argument_types, params); + return std::make_shared::template AggregateFunctionVariadic>( + argument_types, params); + return std::make_shared::template AggregateFunctionVariadic>( + argument_types, params); } } /// "Variadic" method also works as a fallback generic case for a single argument. if (use_exact_hash_function) return std::make_shared::template AggregateFunctionVariadic>(argument_types, params); - else - return std::make_shared::template AggregateFunctionVariadic>(argument_types, params); + return std::make_shared::template AggregateFunctionVariadic>(argument_types, params); } template @@ -270,8 +276,7 @@ AggregateFunctionPtr createAggregateFunctionWithHashType(bool use_64_bit_hash, c { if (use_64_bit_hash) return createAggregateFunctionWithK(argument_types, params); - else - return createAggregateFunctionWithK(argument_types, params); + return createAggregateFunctionWithK(argument_types, params); } /// Let's instantiate these templates in separate translation units, diff --git a/src/AggregateFunctions/AggregateFunctionUniqUpTo.cpp b/src/AggregateFunctions/AggregateFunctionUniqUpTo.cpp index 4e99aa98c36..ec003952965 100644 --- a/src/AggregateFunctions/AggregateFunctionUniqUpTo.cpp +++ b/src/AggregateFunctions/AggregateFunctionUniqUpTo.cpp @@ -324,30 +324,28 @@ AggregateFunctionPtr createAggregateFunctionUniqUpTo(const std::string & name, c WhichDataType which(argument_type); if (res) return res; - else if (which.isDate()) + if (which.isDate()) return std::make_shared>(threshold, argument_types, params); - else if (which.isDate32()) + if (which.isDate32()) return std::make_shared>(threshold, argument_types, params); - else if (which.isDateTime()) + if (which.isDateTime()) return std::make_shared>(threshold, argument_types, params); - else if (which.isStringOrFixedString()) + if (which.isStringOrFixedString()) return std::make_shared>(threshold, argument_types, params); - else if (which.isUUID()) + if (which.isUUID()) return std::make_shared>(threshold, argument_types, params); - else if (which.isTuple()) + if (which.isTuple()) { if (use_exact_hash_function) return std::make_shared>(argument_types, params, threshold); - else - return std::make_shared>(argument_types, params, threshold); + return std::make_shared>(argument_types, params, threshold); } } /// "Variadic" method also works as a fallback generic case for single argument. if (use_exact_hash_function) return std::make_shared>(argument_types, params, threshold); - else - return std::make_shared>(argument_types, params, threshold); + return std::make_shared>(argument_types, params, threshold); } } diff --git a/src/AggregateFunctions/AggregateFunctionWindowFunnel.cpp b/src/AggregateFunctions/AggregateFunctionWindowFunnel.cpp index 809d8b7347c..44eebfc21a9 100644 --- a/src/AggregateFunctions/AggregateFunctionWindowFunnel.cpp +++ b/src/AggregateFunctions/AggregateFunctionWindowFunnel.cpp @@ -180,10 +180,9 @@ private: { if (first_event) break; - else - continue; + continue; } - else if (event_idx == 0) + if (event_idx == 0) { events_timestamp[0] = std::make_pair(timestamp, timestamp); first_event = true; @@ -326,10 +325,11 @@ createAggregateFunctionWindowFunnel(const std::string & name, const DataTypes & WhichDataType which(arguments.front().get()); if (res) return res; - else if (which.isDate()) + if (which.isDate()) return std::make_shared>>(arguments, params); - else if (which.isDateTime()) - return std::make_shared>>(arguments, params); + if (which.isDateTime()) + return std::make_shared>>( + arguments, params); throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of first argument of aggregate function {}, must " diff --git a/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.cpp b/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.cpp index 178915ed208..d1110a893d2 100644 --- a/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.cpp +++ b/src/AggregateFunctions/Combinators/AggregateFunctionDistinct.cpp @@ -50,10 +50,8 @@ public: return std::make_shared< AggregateFunctionDistinct< AggregateFunctionDistinctSingleGenericData>>(nested_function, arguments, params); - else - return std::make_shared< - AggregateFunctionDistinct< - AggregateFunctionDistinctSingleGenericData>>(nested_function, arguments, params); + return std::make_shared>>( + nested_function, arguments, params); } return std::make_shared>(nested_function, arguments, params); diff --git a/src/AggregateFunctions/Combinators/AggregateFunctionIf.cpp b/src/AggregateFunctions/Combinators/AggregateFunctionIf.cpp index 3e21ffa3418..08ce6fe1413 100644 --- a/src/AggregateFunctions/Combinators/AggregateFunctionIf.cpp +++ b/src/AggregateFunctions/Combinators/AggregateFunctionIf.cpp @@ -473,28 +473,20 @@ AggregateFunctionPtr AggregateFunctionIf::getOwnNullAdapter( { return std::make_shared>(nested_function->getName(), nested_func, arguments, params); } - else - { - if (need_to_serialize_flag) - return std::make_shared>(nested_function->getName(), nested_func, arguments, params); - else - return std::make_shared>(nested_function->getName(), nested_func, arguments, params); - } + + if (need_to_serialize_flag) + return std::make_shared>(nested_function->getName(), nested_func, arguments, params); + return std::make_shared>(nested_function->getName(), nested_func, arguments, params); } - else + + if (return_type_is_nullable) { - if (return_type_is_nullable) - { - return std::make_shared>(nested_function, arguments, params); - } - else - { - if (need_to_serialize_flag) - return std::make_shared>(nested_function, arguments, params); - else - return std::make_shared>(nested_function, arguments, params); - } + return std::make_shared>(nested_function, arguments, params); } + + if (need_to_serialize_flag) + return std::make_shared>(nested_function, arguments, params); + return std::make_shared>(nested_function, arguments, params); } void registerAggregateFunctionCombinatorIf(AggregateFunctionCombinatorFactory & factory) diff --git a/src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp b/src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp index a25f323c08a..58e7a0f0258 100644 --- a/src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp +++ b/src/AggregateFunctions/Combinators/AggregateFunctionMap.cpp @@ -450,9 +450,8 @@ public: auto action = NullsAction::EMPTY; return aggr_func_factory.get(nested_func_name + "MappedArrays", action, arguments, params, out_properties); } - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Aggregation '{}Map' is not implemented for mapped arrays", - nested_func_name); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Aggregation '{}Map' is not implemented for mapped arrays", nested_func_name); } } }; diff --git a/src/AggregateFunctions/Combinators/AggregateFunctionNull.cpp b/src/AggregateFunctions/Combinators/AggregateFunctionNull.cpp index 7ffacd3af16..24367eb3680 100644 --- a/src/AggregateFunctions/Combinators/AggregateFunctionNull.cpp +++ b/src/AggregateFunctions/Combinators/AggregateFunctionNull.cpp @@ -112,8 +112,7 @@ public: */ if (properties.returns_default_when_only_null) return std::make_shared(arguments, params); - else - return std::make_shared(arguments, params); + return std::make_shared(arguments, params); } assert(nested_function); @@ -137,23 +136,18 @@ public: { return std::make_shared>(nested_function, arguments, params); } - else - { - if (serialize_flag) - return std::make_shared>(nested_function, arguments, params); - else - return std::make_shared>(nested_function, arguments, params); - } + + if (serialize_flag) + return std::make_shared>(nested_function, arguments, params); + return std::make_shared>(nested_function, arguments, params); } - else + + if (return_type_is_nullable) { - if (return_type_is_nullable) - { - return std::make_shared>(nested_function, arguments, params); - } - else - { - return std::make_shared>(nested_function, arguments, params); + return std::make_shared>(nested_function, arguments, params); + } + + return std::make_shared>(nested_function, arguments, params); #if 0 if (serialize_flag) return std::make_shared>(nested_function, arguments, params); @@ -164,8 +158,6 @@ public: return std::make_shared>(nested_function, arguments, params); } #endif - } - } } }; diff --git a/src/AggregateFunctions/Combinators/AggregateFunctionOrFill.cpp b/src/AggregateFunctions/Combinators/AggregateFunctionOrFill.cpp index 2f85ec6c066..db679e6a790 100644 --- a/src/AggregateFunctions/Combinators/AggregateFunctionOrFill.cpp +++ b/src/AggregateFunctions/Combinators/AggregateFunctionOrFill.cpp @@ -37,8 +37,7 @@ public: { if (kind == Kind::OrNull) return std::make_shared>(nested_function, arguments, params); - else - return std::make_shared>(nested_function, arguments, params); + return std::make_shared>(nested_function, arguments, params); } }; diff --git a/src/AggregateFunctions/DDSketch.h b/src/AggregateFunctions/DDSketch.h index e921b64989a..16b6318181c 100644 --- a/src/AggregateFunctions/DDSketch.h +++ b/src/AggregateFunctions/DDSketch.h @@ -120,11 +120,9 @@ public: this->merge(new_sketch); return; } - else - { - DDSketchDenseLogarithmic new_sketch = changeMapping(other.mapping->getGamma()); - copy(new_sketch); - } + + DDSketchDenseLogarithmic new_sketch = changeMapping(other.mapping->getGamma()); + copy(new_sketch); } // If the other sketch is empty, do nothing diff --git a/src/AggregateFunctions/IAggregateFunction.h b/src/AggregateFunctions/IAggregateFunction.h index f8e7051d635..24e242e2dc7 100644 --- a/src/AggregateFunctions/IAggregateFunction.h +++ b/src/AggregateFunctions/IAggregateFunction.h @@ -694,7 +694,7 @@ class IAggregateFunctionDataHelper : public IAggregateFunctionHelper protected: using Data = T; - static Data & data(AggregateDataPtr __restrict place) { return *reinterpret_cast(place); } + static Data & data(const AggregateDataPtr __restrict place) { return *reinterpret_cast(place); } static const Data & data(ConstAggregateDataPtr __restrict place) { return *reinterpret_cast(place); } public: diff --git a/src/AggregateFunctions/QuantileExact.h b/src/AggregateFunctions/QuantileExact.h index 94e321083a7..a5bb964a372 100644 --- a/src/AggregateFunctions/QuantileExact.h +++ b/src/AggregateFunctions/QuantileExact.h @@ -146,7 +146,7 @@ struct QuantileExactExclusive : public QuantileExact if (n >= array.size()) return static_cast(*std::max_element(array.begin(), array.end())); - else if (n < 1) + if (n < 1) return static_cast(*std::min_element(array.begin(), array.end())); ::nth_element(array.begin(), array.begin() + n - 1, array.end()); @@ -211,7 +211,7 @@ struct QuantileExactInclusive : public QuantileExact if (n >= array.size()) return static_cast(*std::max_element(array.begin(), array.end())); - else if (n < 1) + if (n < 1) return static_cast(*std::min_element(array.begin(), array.end())); ::nth_element(array.begin(), array.begin() + n - 1, array.end()); auto * nth_elem = std::min_element(array.begin() + n, array.end()); diff --git a/src/AggregateFunctions/QuantileTDigest.h b/src/AggregateFunctions/QuantileTDigest.h index 4207ea587b1..f915d6c70a3 100644 --- a/src/AggregateFunctions/QuantileTDigest.h +++ b/src/AggregateFunctions/QuantileTDigest.h @@ -416,15 +416,10 @@ public: if (x <= left) return checkOverflow(prev_mean); - else if (x >= right) + if (x >= right) return checkOverflow(c.mean); - else - return checkOverflow(interpolate( - static_cast(x), - static_cast(left), - prev_mean, - static_cast(right), - c.mean)); + return checkOverflow( + interpolate(static_cast(x), static_cast(left), prev_mean, static_cast(right), c.mean)); } sum += c.count; diff --git a/src/AggregateFunctions/QuantileTiming.h b/src/AggregateFunctions/QuantileTiming.h index eef15828fc0..b2758890022 100644 --- a/src/AggregateFunctions/QuantileTiming.h +++ b/src/AggregateFunctions/QuantileTiming.h @@ -736,14 +736,12 @@ public: tiny.prepare(); return tiny.get(level); } - else if (kind == Kind::Medium) + if (kind == Kind::Medium) { return medium.get(level); } - else - { - return large->get(level); - } + + return large->get(level); } /// Get the size values of the quantiles of the `levels` levels. Record `size` results starting with `result` address. diff --git a/src/AggregateFunctions/ReservoirSampler.h b/src/AggregateFunctions/ReservoirSampler.h index 7b6ef1b2dc0..2668e0dc890 100644 --- a/src/AggregateFunctions/ReservoirSampler.h +++ b/src/AggregateFunctions/ReservoirSampler.h @@ -260,8 +260,7 @@ private: /// With a large number of values, we will generate random numbers several times slower. if (limit <= static_cast(pcg32_fast::max())) return rng() % limit; - else - return (static_cast(rng()) * (static_cast(pcg32_fast::max()) + 1ULL) + static_cast(rng())) % limit; + return (static_cast(rng()) * (static_cast(pcg32_fast::max()) + 1ULL) + static_cast(rng())) % limit; } void sortIfNeeded() @@ -277,7 +276,6 @@ private: { if (OnEmpty == ReservoirSamplerOnEmpty::THROW) throw DB::Exception(DB::ErrorCodes::LOGICAL_ERROR, "Quantile of empty ReservoirSampler"); - else - return NanLikeValueConstructor>::getValue(); + return NanLikeValueConstructor>::getValue(); } }; diff --git a/src/AggregateFunctions/ReservoirSamplerDeterministic.h b/src/AggregateFunctions/ReservoirSamplerDeterministic.h index 38a40c73353..0ad8e968358 100644 --- a/src/AggregateFunctions/ReservoirSamplerDeterministic.h +++ b/src/AggregateFunctions/ReservoirSamplerDeterministic.h @@ -271,8 +271,7 @@ private: { if (OnEmpty == ReservoirSamplerDeterministicOnEmpty::THROW) throw DB::Exception(DB::ErrorCodes::LOGICAL_ERROR, "Quantile of empty ReservoirSamplerDeterministic"); - else - return NanLikeValueConstructor>::getValue(); + return NanLikeValueConstructor>::getValue(); } }; diff --git a/src/AggregateFunctions/SingleValueData.cpp b/src/AggregateFunctions/SingleValueData.cpp index 11931acbbc8..797ff432d46 100644 --- a/src/AggregateFunctions/SingleValueData.cpp +++ b/src/AggregateFunctions/SingleValueData.cpp @@ -50,15 +50,13 @@ std::optional SingleValueDataBase::getSmallestIndex(const IColumn & colu index = i; return {index}; } - else - { - constexpr IColumn::PermutationSortDirection direction = IColumn::PermutationSortDirection::Ascending; - constexpr IColumn::PermutationSortStability stability = IColumn::PermutationSortStability::Unstable; - IColumn::Permutation permutation; - constexpr UInt64 limit = 1; - column.getPermutation(direction, stability, limit, nan_null_direction_hint, permutation); - return {permutation[0]}; - } + + constexpr IColumn::PermutationSortDirection direction = IColumn::PermutationSortDirection::Ascending; + constexpr IColumn::PermutationSortStability stability = IColumn::PermutationSortStability::Unstable; + IColumn::Permutation permutation; + constexpr UInt64 limit = 1; + column.getPermutation(direction, stability, limit, nan_null_direction_hint, permutation); + return {permutation[0]}; } std::optional SingleValueDataBase::getGreatestIndex(const IColumn & column, size_t row_begin, size_t row_end) const @@ -77,15 +75,13 @@ std::optional SingleValueDataBase::getGreatestIndex(const IColumn & colu index = i; return {index}; } - else - { - constexpr IColumn::PermutationSortDirection direction = IColumn::PermutationSortDirection::Descending; - constexpr IColumn::PermutationSortStability stability = IColumn::PermutationSortStability::Unstable; - IColumn::Permutation permutation; - constexpr UInt64 limit = 1; - column.getPermutation(direction, stability, limit, nan_null_direction_hint, permutation); - return {permutation[0]}; - } + + constexpr IColumn::PermutationSortDirection direction = IColumn::PermutationSortDirection::Descending; + constexpr IColumn::PermutationSortStability stability = IColumn::PermutationSortStability::Unstable; + IColumn::Permutation permutation; + constexpr UInt64 limit = 1; + column.getPermutation(direction, stability, limit, nan_null_direction_hint, permutation); + return {permutation[0]}; } std::optional SingleValueDataBase::getSmallestIndexNotNullIf( @@ -247,8 +243,7 @@ bool SingleValueDataFixed::setIfSmaller(const SingleValueDataFixed & to, A set(to, arena); return true; } - else - return false; + return false; } template @@ -259,8 +254,7 @@ bool SingleValueDataFixed::setIfGreater(const SingleValueDataFixed & to, A set(to, arena); return true; } - else - return false; + return false; } template @@ -271,8 +265,7 @@ bool SingleValueDataFixed::setIfSmaller(const IColumn & column, size_t row_nu set(column, row_num, arena); return true; } - else - return false; + return false; } template @@ -283,8 +276,7 @@ bool SingleValueDataFixed::setIfGreater(const IColumn & column, size_t row_nu set(column, row_num, arena); return true; } - else - return false; + return false; } template @@ -544,7 +536,7 @@ std::optional SingleValueDataFixed::getGreatestIndexNotNullIf( } return opt; } - else if (!null_map) + if (!null_map) { opt = findExtremeMaxIf(vec.getData().data(), if_map, row_begin, row_end); if (!opt.has_value()) @@ -556,18 +548,17 @@ std::optional SingleValueDataFixed::getGreatestIndexNotNullIf( } return opt; } - else + + auto final_flags = mergeIfAndNullFlags(null_map, if_map, row_begin, row_end); + opt = findExtremeMaxIf(vec.getData().data(), final_flags.get(), row_begin, row_end); + if (!opt.has_value()) + return std::nullopt; + for (size_t i = row_begin; i < row_end; i++) { - auto final_flags = mergeIfAndNullFlags(null_map, if_map, row_begin, row_end); - opt = findExtremeMaxIf(vec.getData().data(), final_flags.get(), row_begin, row_end); - if (!opt.has_value()) - return std::nullopt; - for (size_t i = row_begin; i < row_end; i++) - { - if (final_flags[i] && vec[i] == *opt) - return {i}; - } + if (final_flags[i] && vec[i] == *opt) + return {i}; } + UNREACHABLE(); } else @@ -1218,8 +1209,7 @@ bool SingleValueDataString::setIfSmaller(const IColumn & column, size_t row_num, set(column, row_num, arena); return true; } - else - return false; + return false; } bool SingleValueDataString::setIfSmaller(const SingleValueDataBase & other, Arena * arena) @@ -1230,8 +1220,7 @@ bool SingleValueDataString::setIfSmaller(const SingleValueDataBase & other, Aren changeImpl(to.getStringRef(), arena); return true; } - else - return false; + return false; } @@ -1243,8 +1232,7 @@ bool SingleValueDataString::setIfGreater(const IColumn & column, size_t row_num, set(column, row_num, arena); return true; } - else - return false; + return false; } bool SingleValueDataString::setIfGreater(const SingleValueDataBase & other, Arena * arena) @@ -1255,8 +1243,7 @@ bool SingleValueDataString::setIfGreater(const SingleValueDataBase & other, Aren changeImpl(to.getStringRef(), arena); return true; } - else - return false; + return false; } void SingleValueDataGeneric::insertResultInto(IColumn & to) const @@ -1317,18 +1304,15 @@ bool SingleValueDataGeneric::setIfSmaller(const IColumn & column, size_t row_num set(column, row_num, arena); return true; } - else + + Field new_value; + column.get(row_num, new_value); + if (new_value < value) { - Field new_value; - column.get(row_num, new_value); - if (new_value < value) - { - value = new_value; - return true; - } - else - return false; + value = new_value; + return true; } + return false; } bool SingleValueDataGeneric::setIfSmaller(const SingleValueDataBase & other, Arena *) @@ -1339,8 +1323,7 @@ bool SingleValueDataGeneric::setIfSmaller(const SingleValueDataBase & other, Are value = to.value; return true; } - else - return false; + return false; } bool SingleValueDataGeneric::setIfGreater(const IColumn & column, size_t row_num, Arena * arena) @@ -1350,18 +1333,15 @@ bool SingleValueDataGeneric::setIfGreater(const IColumn & column, size_t row_num set(column, row_num, arena); return true; } - else + + Field new_value; + column.get(row_num, new_value); + if (new_value > value) { - Field new_value; - column.get(row_num, new_value); - if (new_value > value) - { - value = new_value; - return true; - } - else - return false; + value = new_value; + return true; } + return false; } bool SingleValueDataGeneric::setIfGreater(const SingleValueDataBase & other, Arena *) @@ -1372,8 +1352,7 @@ bool SingleValueDataGeneric::setIfGreater(const SingleValueDataBase & other, Are value = to.value; return true; } - else - return false; + return false; } void generateSingleValueFromTypeIndex(TypeIndex idx, SingleValueDataBaseMemoryBlock & data) diff --git a/src/AggregateFunctions/ThetaSketchData.h b/src/AggregateFunctions/ThetaSketchData.h index 99dca27673d..476ecda06fd 100644 --- a/src/AggregateFunctions/ThetaSketchData.h +++ b/src/AggregateFunctions/ThetaSketchData.h @@ -60,10 +60,9 @@ public: { if (sk_union) return static_cast(sk_union->get_result().get_estimate()); - else if (sk_update) + if (sk_update) return static_cast(sk_update->get_estimate()); - else - return 0; + return 0; } void merge(const ThetaSketchData & rhs) diff --git a/src/AggregateFunctions/UniqVariadicHash.cpp b/src/AggregateFunctions/UniqVariadicHash.cpp index 940f0677163..2b20c59dba7 100644 --- a/src/AggregateFunctions/UniqVariadicHash.cpp +++ b/src/AggregateFunctions/UniqVariadicHash.cpp @@ -26,8 +26,7 @@ bool isAllArgumentsContiguousInMemory(const DataTypes & argument_types) if (single_argument_as_tuple) return check_all_arguments_are_contiguous_in_memory(single_argument_as_tuple->getElements()); - else - return check_all_arguments_are_contiguous_in_memory(argument_types); + return check_all_arguments_are_contiguous_in_memory(argument_types); } } diff --git a/src/Analyzer/ColumnTransformers.cpp b/src/Analyzer/ColumnTransformers.cpp index 356344c1aec..d766d9acdd8 100644 --- a/src/Analyzer/ColumnTransformers.cpp +++ b/src/Analyzer/ColumnTransformers.cpp @@ -163,18 +163,16 @@ void ExceptColumnTransformerNode::dumpTreeImpl(WriteBuffer & buffer, FormatState buffer << ", pattern: " << column_matcher->pattern(); return; } - else + + buffer << ", identifiers: "; + + size_t except_column_names_size = except_column_names.size(); + for (size_t i = 0; i < except_column_names_size; ++i) { - buffer << ", identifiers: "; + buffer << except_column_names[i]; - size_t except_column_names_size = except_column_names.size(); - for (size_t i = 0; i < except_column_names_size; ++i) - { - buffer << except_column_names[i]; - - if (i + 1 != except_column_names_size) - buffer << ", "; - } + if (i + 1 != except_column_names_size) + buffer << ", "; } } @@ -190,9 +188,9 @@ bool ExceptColumnTransformerNode::isEqualImpl(const IQueryTreeNode & rhs, Compar if (!column_matcher && !rhs_column_matcher) return true; - else if (column_matcher && !rhs_column_matcher) + if (column_matcher && !rhs_column_matcher) return false; - else if (!column_matcher && rhs_column_matcher) + if (!column_matcher && rhs_column_matcher) return false; return column_matcher->pattern() == rhs_column_matcher->pattern(); diff --git a/src/Analyzer/FunctionNode.cpp b/src/Analyzer/FunctionNode.cpp index 8e4e0725a2d..1ad7e7996c7 100644 --- a/src/Analyzer/FunctionNode.cpp +++ b/src/Analyzer/FunctionNode.cpp @@ -173,9 +173,9 @@ bool FunctionNode::isEqualImpl(const IQueryTreeNode & rhs, CompareOptions compar if (lhs_result_type && rhs_result_type && !lhs_result_type->equals(*rhs_result_type)) return false; - else if (lhs_result_type && !rhs_result_type) + if (lhs_result_type && !rhs_result_type) return false; - else if (!lhs_result_type && rhs_result_type) + if (!lhs_result_type && rhs_result_type) return false; return true; diff --git a/src/Analyzer/IQueryTreeNode.cpp b/src/Analyzer/IQueryTreeNode.cpp index cfba4b41410..a7284ba1aee 100644 --- a/src/Analyzer/IQueryTreeNode.cpp +++ b/src/Analyzer/IQueryTreeNode.cpp @@ -127,9 +127,9 @@ bool IQueryTreeNode::isEqual(const IQueryTreeNode & rhs, CompareOptions compare_ if (!lhs_child && !rhs_child) continue; - else if (lhs_child && !rhs_child) + if (lhs_child && !rhs_child) return false; - else if (!lhs_child && rhs_child) + if (!lhs_child && rhs_child) return false; nodes_to_process.emplace_back(lhs_child.get(), rhs_child.get()); @@ -150,9 +150,9 @@ bool IQueryTreeNode::isEqual(const IQueryTreeNode & rhs, CompareOptions compare_ if (!lhs_strong_pointer && !rhs_strong_pointer) continue; - else if (lhs_strong_pointer && !rhs_strong_pointer) + if (lhs_strong_pointer && !rhs_strong_pointer) return false; - else if (!lhs_strong_pointer && rhs_strong_pointer) + if (!lhs_strong_pointer && rhs_strong_pointer) return false; nodes_to_process.emplace_back(lhs_strong_pointer.get(), rhs_strong_pointer.get()); diff --git a/src/Analyzer/InDepthQueryTreeVisitor.h b/src/Analyzer/InDepthQueryTreeVisitor.h index 67e3b75d8b5..95d4bcfedf7 100644 --- a/src/Analyzer/InDepthQueryTreeVisitor.h +++ b/src/Analyzer/InDepthQueryTreeVisitor.h @@ -202,8 +202,7 @@ private: } return; } - else - visit(child); + visit(child); } void visitChildren(VisitQueryTreeNodeType & expression) diff --git a/src/Analyzer/MatcherNode.cpp b/src/Analyzer/MatcherNode.cpp index 341c4b8eec7..c3608af6319 100644 --- a/src/Analyzer/MatcherNode.cpp +++ b/src/Analyzer/MatcherNode.cpp @@ -173,9 +173,9 @@ bool MatcherNode::isEqualImpl(const IQueryTreeNode & rhs, CompareOptions) const if (!columns_matcher && !rhs_columns_matcher) return true; - else if (columns_matcher && !rhs_columns_matcher) + if (columns_matcher && !rhs_columns_matcher) return false; - else if (!columns_matcher && rhs_columns_matcher) + if (!columns_matcher && rhs_columns_matcher) return false; return columns_matcher->pattern() == rhs_columns_matcher->pattern(); diff --git a/src/Analyzer/Passes/AggregateFunctionsArithmericOperationsPass.cpp b/src/Analyzer/Passes/AggregateFunctionsArithmericOperationsPass.cpp index b191608cf8a..23cc9ecf43c 100644 --- a/src/Analyzer/Passes/AggregateFunctionsArithmericOperationsPass.cpp +++ b/src/Analyzer/Passes/AggregateFunctionsArithmericOperationsPass.cpp @@ -118,10 +118,9 @@ public: { if (aggregate_function_name == "min") return "max"; - else if (aggregate_function_name == "max") + if (aggregate_function_name == "max") return "min"; - else - return aggregate_function_name; + return aggregate_function_name; }; size_t arithmetic_function_argument_index = 0; diff --git a/src/Analyzer/Passes/CNF.cpp b/src/Analyzer/Passes/CNF.cpp index 71549f9e71d..3dca295a439 100644 --- a/src/Analyzer/Passes/CNF.cpp +++ b/src/Analyzer/Passes/CNF.cpp @@ -486,8 +486,7 @@ CNF & CNF::reduce() statements = filterCNFSubsets(statements); return *this; } - else - statements = new_statements; + statements = new_statements; } } diff --git a/src/Analyzer/Passes/ConvertQueryToCNFPass.cpp b/src/Analyzer/Passes/ConvertQueryToCNFPass.cpp index ddac55c1946..5ac04739a9c 100644 --- a/src/Analyzer/Passes/ConvertQueryToCNFPass.cpp +++ b/src/Analyzer/Passes/ConvertQueryToCNFPass.cpp @@ -184,7 +184,7 @@ StorageSnapshotPtr getStorageSnapshot(const QueryTreeNodePtr & node) StorageSnapshotPtr storage_snapshot{nullptr}; if (auto * table_node = node->as()) return table_node->getStorageSnapshot(); - else if (auto * table_function_node = node->as()) + if (auto * table_function_node = node->as()) return table_function_node->getStorageSnapshot(); return nullptr; diff --git a/src/Analyzer/Passes/IfTransformStringsToEnumPass.cpp b/src/Analyzer/Passes/IfTransformStringsToEnumPass.cpp index b205efe4f88..a38c44f5d48 100644 --- a/src/Analyzer/Passes/IfTransformStringsToEnumPass.cpp +++ b/src/Analyzer/Passes/IfTransformStringsToEnumPass.cpp @@ -43,8 +43,7 @@ DataTypePtr getEnumType(const std::set & string_values) { if (string_values.size() >= 255) return getDataEnumType(string_values); - else - return getDataEnumType(string_values); + return getDataEnumType(string_values); } /// if(arg1, arg2, arg3) will be transformed to if(arg1, _CAST(arg2, Enum...), _CAST(arg3, Enum...)) diff --git a/src/Analyzer/Passes/OptimizeDateOrDateTimeConverterWithPreimagePass.cpp b/src/Analyzer/Passes/OptimizeDateOrDateTimeConverterWithPreimagePass.cpp index e4490789cab..04f74174b8c 100644 --- a/src/Analyzer/Passes/OptimizeDateOrDateTimeConverterWithPreimagePass.cpp +++ b/src/Analyzer/Passes/OptimizeDateOrDateTimeConverterWithPreimagePass.cpp @@ -165,27 +165,26 @@ private: createFunctionNode("greaterOrEquals", column_node, std::make_shared(start_date_or_date_time)), createFunctionNode("less", column_node, std::make_shared(end_date_or_date_time))); } - else if (comparator == "notEquals") + if (comparator == "notEquals") { return createFunctionNode( "or", createFunctionNode("less", column_node, std::make_shared(start_date_or_date_time)), createFunctionNode("greaterOrEquals", column_node, std::make_shared(end_date_or_date_time))); } - else if (comparator == "greater") + if (comparator == "greater") { return createFunctionNode("greaterOrEquals", column_node, std::make_shared(end_date_or_date_time)); } - else if (comparator == "lessOrEquals") + if (comparator == "lessOrEquals") { return createFunctionNode("less", column_node, std::make_shared(end_date_or_date_time)); } - else if (comparator == "less" || comparator == "greaterOrEquals") + if (comparator == "less" || comparator == "greaterOrEquals") { return createFunctionNode(comparator, column_node, std::make_shared(start_date_or_date_time)); } - else [[unlikely]] - { + [[unlikely]] { throw Exception( ErrorCodes::LOGICAL_ERROR, "Expected equals, notEquals, less, lessOrEquals, greater, greaterOrEquals. Actual {}", diff --git a/src/Analyzer/Resolve/IdentifierResolver.cpp b/src/Analyzer/Resolve/IdentifierResolver.cpp index 000e7ff391a..15a90c52a2a 100644 --- a/src/Analyzer/Resolve/IdentifierResolver.cpp +++ b/src/Analyzer/Resolve/IdentifierResolver.cpp @@ -552,9 +552,9 @@ QueryTreeNodePtr IdentifierResolver::tryResolveIdentifierFromExpressionArguments auto node_type = it->second->getNodeType(); if (identifier_lookup.isExpressionLookup() && !isExpressionNodeType(node_type)) return {}; - else if (identifier_lookup.isTableExpressionLookup() && !isTableExpressionNodeType(node_type)) + if (identifier_lookup.isTableExpressionLookup() && !isTableExpressionNodeType(node_type)) return {}; - else if (identifier_lookup.isFunctionLookup() && !isFunctionExpressionNodeType(node_type)) + if (identifier_lookup.isFunctionLookup() && !isFunctionExpressionNodeType(node_type)) return {}; if (!resolve_full_identifier && identifier_lookup.identifier.isCompound() && identifier_lookup.isExpressionLookup()) @@ -638,10 +638,9 @@ bool IdentifierResolver::tryBindIdentifierToTableExpression(const IdentifierLook if (parts_size == 1 && path_start == table_name) return true; - else if (parts_size == 2 && path_start == database_name && identifier[1] == table_name) + if (parts_size == 2 && path_start == database_name && identifier[1] == table_name) return true; - else - return false; + return false; } if (table_expression_data.hasFullIdentifierName(IdentifierView(identifier)) || table_expression_data.canBindIdentifier(IdentifierView(identifier))) @@ -910,10 +909,9 @@ QueryTreeNodePtr IdentifierResolver::tryResolveIdentifierFromTableExpression(con if (parts_size == 1 && path_start == table_name) return table_expression_node; - else if (parts_size == 2 && path_start == database_name && identifier[1] == table_name) + if (parts_size == 2 && path_start == database_name && identifier[1] == table_name) return table_expression_node; - else - return {}; + return {}; } /** If identifier first part binds to some column start or table has full identifier name. Then we can try to find whole identifier in table. diff --git a/src/Analyzer/Resolve/QueryAnalyzer.cpp b/src/Analyzer/Resolve/QueryAnalyzer.cpp index 8ba64b0d986..d4d33dcb11b 100644 --- a/src/Analyzer/Resolve/QueryAnalyzer.cpp +++ b/src/Analyzer/Resolve/QueryAnalyzer.cpp @@ -1219,9 +1219,10 @@ QueryTreeNodePtr QueryAnalyzer::tryResolveIdentifierFromAliases(const Identifier scope, identifier_resolve_settings.allow_to_check_join_tree /* can_be_not_found */); } - else if (identifier_lookup.isFunctionLookup() || identifier_lookup.isTableExpressionLookup()) + if (identifier_lookup.isFunctionLookup() || identifier_lookup.isTableExpressionLookup()) { - throw Exception(ErrorCodes::BAD_ARGUMENTS, + throw Exception( + ErrorCodes::BAD_ARGUMENTS, "Compound identifier '{}' cannot be resolved as {}. In scope {}", identifier_lookup.identifier.getFullName(), identifier_lookup.isFunctionLookup() ? "function" : "table expression", @@ -1307,7 +1308,7 @@ IdentifierResolveResult QueryAnalyzer::tryResolveIdentifierInParentScopes(const { return lookup_result; } - else if (auto * resolved_function = resolved_identifier->as()) + if (auto * resolved_function = resolved_identifier->as()) { /// Special case: scalar subquery was executed and replaced by __getScalar function. /// Handle it as a constant. @@ -3173,14 +3174,14 @@ ProjectionNames QueryAnalyzer::resolveFunction(QueryTreeNodePtr & node, Identifi node = std::move(result_list); return result_projection_names; } - else if (function_name == "grouping") + if (function_name == "grouping") { /// It is responsibility of planner to perform additional handling of grouping function if (function_arguments_size == 0) - throw Exception(ErrorCodes::TOO_FEW_ARGUMENTS_FOR_FUNCTION, - "Function GROUPING expects at least one argument"); - else if (function_arguments_size > 64) - throw Exception(ErrorCodes::TOO_MANY_ARGUMENTS_FOR_FUNCTION, + throw Exception(ErrorCodes::TOO_FEW_ARGUMENTS_FOR_FUNCTION, "Function GROUPING expects at least one argument"); + if (function_arguments_size > 64) + throw Exception( + ErrorCodes::TOO_MANY_ARGUMENTS_FOR_FUNCTION, "Function GROUPING can have up to 64 arguments, but {} provided", function_arguments_size); checkFunctionNodeHasEmptyNullsAction(function_node); @@ -3744,11 +3745,11 @@ ProjectionNames QueryAnalyzer::resolveExpressionNode( resolved_expression_it = resolved_expressions.find(node); if (resolved_expression_it != resolved_expressions.end()) return resolved_expression_it->second; - else - throw Exception(ErrorCodes::LOGICAL_ERROR, - "Identifier '{}' resolve into list node and list node projection names are not initialized. In scope {}", - unresolved_identifier.getFullName(), - scope.scope_node->formatASTForErrorMessage()); + throw Exception( + ErrorCodes::LOGICAL_ERROR, + "Identifier '{}' resolve into list node and list node projection names are not initialized. In scope {}", + unresolved_identifier.getFullName(), + scope.scope_node->formatASTForErrorMessage()); } if (result_projection_names.empty()) @@ -4212,7 +4213,7 @@ NamesAndTypes QueryAnalyzer::resolveProjectionExpressionNodeList(QueryTreeNodePt for (size_t i = 0; i < projection_nodes_size; ++i) { - auto projection_node = projection_nodes[i]; + const auto & projection_node = projection_nodes[i]; if (!IdentifierResolver::isExpressionNodeType(projection_node->getNodeType())) throw Exception(ErrorCodes::UNSUPPORTED_METHOD, @@ -4628,10 +4629,7 @@ void QueryAnalyzer::resolveTableFunction(QueryTreeNodePtr & table_function_node, "Unknown table function {}. Maybe you meant: {}", table_function_name, DB::toString(hints)); - else - throw Exception(ErrorCodes::UNKNOWN_FUNCTION, - "Unknown table function {}", - table_function_name); + throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "Unknown table function {}", table_function_name); } QueryTreeNodes result_table_function_arguments; @@ -4667,7 +4665,7 @@ void QueryAnalyzer::resolveTableFunction(QueryTreeNodePtr & table_function_node, continue; } - else if (auto * table_function_argument_function = table_function_argument->as()) + if (auto * table_function_argument_function = table_function_argument->as()) { const auto & table_function_argument_function_name = table_function_argument_function->getFunctionName(); if (TableFunctionFactory::instance().isTableFunctionName(table_function_argument_function_name)) diff --git a/src/Analyzer/Resolve/QueryExpressionsAliasVisitor.h b/src/Analyzer/Resolve/QueryExpressionsAliasVisitor.h index 31b2f07b97a..9824f4a2570 100644 --- a/src/Analyzer/Resolve/QueryExpressionsAliasVisitor.h +++ b/src/Analyzer/Resolve/QueryExpressionsAliasVisitor.h @@ -50,7 +50,7 @@ public: updateAliasesIfNeeded(child, true /*is_lambda_node*/); return false; } - else if (auto * query_tree_node = child->as()) + if (auto * query_tree_node = child->as()) { if (query_tree_node->isCTE()) return false; @@ -58,7 +58,7 @@ public: updateAliasesIfNeeded(child, false /*is_lambda_node*/); return false; } - else if (auto * union_node = child->as()) + if (auto * union_node = child->as()) { if (union_node->isCTE()) return false; diff --git a/src/Analyzer/SortNode.cpp b/src/Analyzer/SortNode.cpp index 25c9c726d70..e891046626a 100644 --- a/src/Analyzer/SortNode.cpp +++ b/src/Analyzer/SortNode.cpp @@ -81,9 +81,9 @@ bool SortNode::isEqualImpl(const IQueryTreeNode & rhs, CompareOptions) const if (!collator && !rhs_typed.collator) return true; - else if (collator && !rhs_typed.collator) + if (collator && !rhs_typed.collator) return false; - else if (!collator && rhs_typed.collator) + if (!collator && rhs_typed.collator) return false; return collator->getLocale() == rhs_typed.collator->getLocale(); diff --git a/src/Analyzer/UnionNode.cpp b/src/Analyzer/UnionNode.cpp index 77f6921f939..6f70f01e519 100644 --- a/src/Analyzer/UnionNode.cpp +++ b/src/Analyzer/UnionNode.cpp @@ -170,7 +170,7 @@ bool UnionNode::isEqualImpl(const IQueryTreeNode & rhs, CompareOptions) const if (recursive_cte_table && rhs_typed.recursive_cte_table && recursive_cte_table->getStorageID() != rhs_typed.recursive_cte_table->getStorageID()) return false; - else if ((recursive_cte_table && !rhs_typed.recursive_cte_table) || (!recursive_cte_table && rhs_typed.recursive_cte_table)) + if ((recursive_cte_table && !rhs_typed.recursive_cte_table) || (!recursive_cte_table && rhs_typed.recursive_cte_table)) return false; return is_subquery == rhs_typed.is_subquery && is_cte == rhs_typed.is_cte && is_recursive_cte == rhs_typed.is_recursive_cte diff --git a/src/Analyzer/Utils.cpp b/src/Analyzer/Utils.cpp index c737822282c..c73400532ba 100644 --- a/src/Analyzer/Utils.cpp +++ b/src/Analyzer/Utils.cpp @@ -156,19 +156,19 @@ std::string getGlobalInFunctionNameForLocalInFunctionName(const std::string & fu { if (function_name == "in") return "globalIn"; - else if (function_name == "notIn") + if (function_name == "notIn") return "globalNotIn"; - else if (function_name == "nullIn") + if (function_name == "nullIn") return "globalNullIn"; - else if (function_name == "notNullIn") + if (function_name == "notNullIn") return "globalNotNullIn"; - else if (function_name == "inIgnoreSet") + if (function_name == "inIgnoreSet") return "globalInIgnoreSet"; - else if (function_name == "notInIgnoreSet") + if (function_name == "notInIgnoreSet") return "globalNotInIgnoreSet"; - else if (function_name == "nullInIgnoreSet") + if (function_name == "nullInIgnoreSet") return "globalNullInIgnoreSet"; - else if (function_name == "notNullInIgnoreSet") + if (function_name == "notNullInIgnoreSet") return "globalNotNullInIgnoreSet"; throw Exception(ErrorCodes::BAD_ARGUMENTS, "Invalid local IN function name {}", function_name); diff --git a/src/Analyzer/ValidationUtils.cpp b/src/Analyzer/ValidationUtils.cpp index a8274799b1b..1070c92d8ad 100644 --- a/src/Analyzer/ValidationUtils.cpp +++ b/src/Analyzer/ValidationUtils.cpp @@ -173,9 +173,9 @@ private: if (!lhs_child && !rhs_child) continue; - else if (lhs_child && !rhs_child) + if (lhs_child && !rhs_child) return false; - else if (!lhs_child && rhs_child) + if (!lhs_child && rhs_child) return false; nodes_to_process.emplace_back(lhs_child.get(), rhs_child.get()); diff --git a/src/Backups/BackupEntriesCollector.cpp b/src/Backups/BackupEntriesCollector.cpp index 752691dd9ce..ae73630d41c 100644 --- a/src/Backups/BackupEntriesCollector.cpp +++ b/src/Backups/BackupEntriesCollector.cpp @@ -182,17 +182,15 @@ Strings BackupEntriesCollector::setStage(const String & new_stage, const String { return backup_coordination->waitForStage(new_stage, on_cluster_first_sync_timeout); } - else if (new_stage.starts_with(Stage::GATHERING_METADATA)) + if (new_stage.starts_with(Stage::GATHERING_METADATA)) { auto current_time = std::chrono::steady_clock::now(); auto end_of_timeout = std::max(current_time, collect_metadata_end_time); return backup_coordination->waitForStage( new_stage, std::chrono::duration_cast(end_of_timeout - current_time)); } - else - { - return backup_coordination->waitForStage(new_stage); - } + + return backup_coordination->waitForStage(new_stage); } void BackupEntriesCollector::checkIsQueryCancelled() const @@ -716,23 +714,20 @@ bool BackupEntriesCollector::compareWithPrevious(String & mismatch_description) { if (mismatch->first == p_mismatch->first) return {MismatchType::CHANGED, mismatch->first}; - else if (mismatch->first < p_mismatch->first) + if (mismatch->first < p_mismatch->first) return {MismatchType::ADDED, mismatch->first}; - else - return {MismatchType::REMOVED, mismatch->first}; + return {MismatchType::REMOVED, mismatch->first}; } - else if (mismatch != metadata.end()) + if (mismatch != metadata.end()) { return {MismatchType::ADDED, mismatch->first}; } - else if (p_mismatch != previous_metadata.end()) + if (p_mismatch != previous_metadata.end()) { return {MismatchType::REMOVED, p_mismatch->first}; } - else - { - return {MismatchType::NONE, {}}; - } + + return {MismatchType::NONE, {}}; }; /// Databases must be the same as during the previous scan. diff --git a/src/Backups/BackupEntryFromAppendOnlyFile.cpp b/src/Backups/BackupEntryFromAppendOnlyFile.cpp index 5303d9abffd..083983340f4 100644 --- a/src/Backups/BackupEntryFromAppendOnlyFile.cpp +++ b/src/Backups/BackupEntryFromAppendOnlyFile.cpp @@ -14,10 +14,9 @@ namespace { if (!unencrypted_file_size) return copy_encrypted ? disk->getEncryptedFileSize(file_path) : disk->getFileSize(file_path); - else if (copy_encrypted) + if (copy_encrypted) return disk->getEncryptedFileSize(*unencrypted_file_size); - else - return *unencrypted_file_size; + return *unencrypted_file_size; } } diff --git a/src/Backups/BackupEntryFromImmutableFile.cpp b/src/Backups/BackupEntryFromImmutableFile.cpp index 77ebf6232d4..d5293f83331 100644 --- a/src/Backups/BackupEntryFromImmutableFile.cpp +++ b/src/Backups/BackupEntryFromImmutableFile.cpp @@ -39,8 +39,7 @@ std::unique_ptr BackupEntryFromImmutableFile::getReadBuffer( { if (copy_encrypted) return disk->readEncryptedFile(file_path, read_settings); - else - return disk->readFile(file_path, read_settings); + return disk->readFile(file_path, read_settings); } UInt64 BackupEntryFromImmutableFile::getSize() const diff --git a/src/Backups/BackupIO_Default.cpp b/src/Backups/BackupIO_Default.cpp index 77fd4532c8f..553d0c3c3c9 100644 --- a/src/Backups/BackupIO_Default.cpp +++ b/src/Backups/BackupIO_Default.cpp @@ -85,8 +85,7 @@ void BackupWriterDefault::copyFileFromDisk(const String & path_in_backup, DiskPt { if (copy_encrypted) return src_disk->readEncryptedFile(src_path, settings); - else - return src_disk->readFile(src_path, settings); + return src_disk->readFile(src_path, settings); }; copyDataToFile(path_in_backup, create_read_buffer, start_pos, length); diff --git a/src/Backups/BackupIO_File.cpp b/src/Backups/BackupIO_File.cpp index 13d52c448ac..681513bf7ce 100644 --- a/src/Backups/BackupIO_File.cpp +++ b/src/Backups/BackupIO_File.cpp @@ -132,7 +132,7 @@ void BackupWriterFile::copyFileFromDisk(const String & path_in_backup, DiskPtr s /// std::filesystem::copy() can copy from a single file only. if (auto blob_path = src_disk->getBlobPath(src_path); blob_path.size() == 1) { - auto abs_source_path = blob_path[0]; + const auto & abs_source_path = blob_path[0]; /// std::filesystem::copy() can copy a file as a whole only. if ((start_pos == 0) && (length == fs::file_size(abs_source_path))) diff --git a/src/Backups/BackupImpl.cpp b/src/Backups/BackupImpl.cpp index 23f067a62f5..b95a2e10b4d 100644 --- a/src/Backups/BackupImpl.cpp +++ b/src/Backups/BackupImpl.cpp @@ -792,18 +792,16 @@ std::unique_ptr BackupImpl::readFileImpl(const SizeAndChecks /// Data comes completely from this backup, the base backup isn't used. return read_buffer; } - else if (info.size == info.base_size) + if (info.size == info.base_size) { /// Data comes completely from the base backup (nothing comes from this backup). return base_read_buffer; } - else - { - /// The beginning of the data comes from the base backup, - /// and the ending comes from this backup. - return std::make_unique( - std::move(base_read_buffer), info.base_size, std::move(read_buffer), info.size - info.base_size); - } + + /// The beginning of the data comes from the base backup, + /// and the ending comes from this backup. + return std::make_unique( + std::move(base_read_buffer), info.base_size, std::move(read_buffer), info.size - info.base_size); } size_t BackupImpl::copyFileToDisk(const String & file_name, diff --git a/src/Backups/BackupsWorker.cpp b/src/Backups/BackupsWorker.cpp index 79f5d9eeb47..d3889295598 100644 --- a/src/Backups/BackupsWorker.cpp +++ b/src/Backups/BackupsWorker.cpp @@ -90,10 +90,8 @@ namespace backup_settings.internal, context->getProcessListElement()); } - else - { - return std::make_shared(!backup_settings.deduplicate_files); - } + + return std::make_shared(!backup_settings.deduplicate_files); } std::shared_ptr @@ -128,10 +126,8 @@ namespace restore_settings.internal, context->getProcessListElement()); } - else - { - return std::make_shared(); - } + + return std::make_shared(); } /// Sends information about an exception to IBackupCoordination or IRestoreCoordination. @@ -200,16 +196,14 @@ namespace { if (getCurrentExceptionCode() == ErrorCodes::QUERY_WAS_CANCELLED) return BackupStatus::BACKUP_CANCELLED; - else - return BackupStatus::BACKUP_FAILED; + return BackupStatus::BACKUP_FAILED; } BackupStatus getRestoreStatusFromCurrentException() { if (getCurrentExceptionCode() == ErrorCodes::QUERY_WAS_CANCELLED) return BackupStatus::RESTORE_CANCELLED; - else - return BackupStatus::RESTORE_FAILED; + return BackupStatus::RESTORE_FAILED; } /// Used to change num_active_backups. @@ -416,8 +410,7 @@ OperationID BackupsWorker::start(const ASTPtr & backup_or_restore_query, Context const ASTBackupQuery & backup_query = typeid_cast(*backup_or_restore_query); if (backup_query.kind == ASTBackupQuery::Kind::BACKUP) return startMakingBackup(backup_or_restore_query, context); - else - return startRestoring(backup_or_restore_query, context); + return startRestoring(backup_or_restore_query, context); } @@ -1077,8 +1070,7 @@ void BackupsWorker::setStatus(const String & id, BackupStatus status, bool throw { if (throw_if_error) throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown backup ID {}", id); - else - return; + return; } auto & extended_info = it->second; diff --git a/src/Backups/registerBackupEngineAzureBlobStorage.cpp b/src/Backups/registerBackupEngineAzureBlobStorage.cpp index 45f0386375a..4c7aae6ef9c 100644 --- a/src/Backups/registerBackupEngineAzureBlobStorage.cpp +++ b/src/Backups/registerBackupEngineAzureBlobStorage.cpp @@ -144,30 +144,29 @@ void registerBackupEngineAzureBlobStorage(BackupFactory & factory) /* use_same_s3_credentials_for_base_backup*/ false, params.use_same_password_for_base_backup); } - else - { - auto writer = std::make_shared( - connection_params, - blob_path, - params.allow_azure_native_copy, - params.read_settings, - params.write_settings, - params.context, - params.azure_attempt_to_create_container); - return std::make_unique( - params.backup_info, - archive_params, - params.base_backup_info, - writer, - params.context, - params.is_internal_backup, - params.backup_coordination, - params.backup_uuid, - params.deduplicate_files, - /* use_same_s3_credentials_for_base_backup */ false, - params.use_same_password_for_base_backup); - } + auto writer = std::make_shared( + connection_params, + blob_path, + params.allow_azure_native_copy, + params.read_settings, + params.write_settings, + params.context, + params.azure_attempt_to_create_container); + + return std::make_unique( + params.backup_info, + archive_params, + params.base_backup_info, + writer, + params.context, + params.is_internal_backup, + params.backup_coordination, + params.backup_uuid, + params.deduplicate_files, + /* use_same_s3_credentials_for_base_backup */ false, + params.use_same_password_for_base_backup); + #else throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "AzureBlobStorage support is disabled"); #endif diff --git a/src/Backups/registerBackupEngineS3.cpp b/src/Backups/registerBackupEngineS3.cpp index 79e3e945557..709cc152fe3 100644 --- a/src/Backups/registerBackupEngineS3.cpp +++ b/src/Backups/registerBackupEngineS3.cpp @@ -123,31 +123,31 @@ void registerBackupEngineS3(BackupFactory & factory) params.use_same_s3_credentials_for_base_backup, params.use_same_password_for_base_backup); } - else - { - auto writer = std::make_shared(S3::URI{s3_uri}, - access_key_id, - secret_access_key, - params.allow_s3_native_copy, - params.s3_storage_class, - params.read_settings, - params.write_settings, - params.context, - params.is_internal_backup); - return std::make_unique( - params.backup_info, - archive_params, - params.base_backup_info, - writer, - params.context, - params.is_internal_backup, - params.backup_coordination, - params.backup_uuid, - params.deduplicate_files, - params.use_same_s3_credentials_for_base_backup, - params.use_same_password_for_base_backup); - } + auto writer = std::make_shared( + S3::URI{s3_uri}, + access_key_id, + secret_access_key, + params.allow_s3_native_copy, + params.s3_storage_class, + params.read_settings, + params.write_settings, + params.context, + params.is_internal_backup); + + return std::make_unique( + params.backup_info, + archive_params, + params.base_backup_info, + writer, + params.context, + params.is_internal_backup, + params.backup_coordination, + params.backup_uuid, + params.deduplicate_files, + params.use_same_s3_credentials_for_base_backup, + params.use_same_password_for_base_backup); + #else throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "S3 support is disabled"); #endif diff --git a/src/Backups/registerBackupEnginesFileAndDisk.cpp b/src/Backups/registerBackupEnginesFileAndDisk.cpp index c486f79a77a..1606a84862c 100644 --- a/src/Backups/registerBackupEnginesFileAndDisk.cpp +++ b/src/Backups/registerBackupEnginesFileAndDisk.cpp @@ -181,26 +181,24 @@ void registerBackupEnginesFileAndDisk(BackupFactory & factory) params.use_same_s3_credentials_for_base_backup, params.use_same_password_for_base_backup); } + + std::shared_ptr writer; + if (engine_name == "File") + writer = std::make_shared(path, params.read_settings, params.write_settings); else - { - std::shared_ptr writer; - if (engine_name == "File") - writer = std::make_shared(path, params.read_settings, params.write_settings); - else - writer = std::make_shared(disk, path, params.read_settings, params.write_settings); - return std::make_unique( - params.backup_info, - archive_params, - params.base_backup_info, - writer, - params.context, - params.is_internal_backup, - params.backup_coordination, - params.backup_uuid, - params.deduplicate_files, - params.use_same_s3_credentials_for_base_backup, - params.use_same_password_for_base_backup); - } + writer = std::make_shared(disk, path, params.read_settings, params.write_settings); + return std::make_unique( + params.backup_info, + archive_params, + params.base_backup_info, + writer, + params.context, + params.is_internal_backup, + params.backup_coordination, + params.backup_uuid, + params.deduplicate_files, + params.use_same_s3_credentials_for_base_backup, + params.use_same_password_for_base_backup); }; factory.registerBackupEngine("File", creator_fn); diff --git a/src/BridgeHelper/XDBCBridgeHelper.h b/src/BridgeHelper/XDBCBridgeHelper.h index b75ccbeedc9..e5ade5d4447 100644 --- a/src/BridgeHelper/XDBCBridgeHelper.h +++ b/src/BridgeHelper/XDBCBridgeHelper.h @@ -242,7 +242,8 @@ protected: if (character.length() > 1) throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Failed to parse quoting style from '{}' for service {}", character, BridgeHelperMixin::serviceAlias()); - else if (character.empty()) + + if (character.empty()) quote_style = IdentifierQuotingStyle::Backticks; else if (character[0] == '`') quote_style = IdentifierQuotingStyle::Backticks; diff --git a/src/Client/ClientBase.cpp b/src/Client/ClientBase.cpp index 2377a013425..8a0228ee012 100644 --- a/src/Client/ClientBase.cpp +++ b/src/Client/ClientBase.cpp @@ -1578,8 +1578,7 @@ void ClientBase::processInsertQuery(const String & query_to_execute, ASTPtr pars const auto & settings = client_context->getSettingsRef(); if (settings[Setting::throw_if_no_data_to_insert]) throw Exception(ErrorCodes::NO_DATA_TO_INSERT, "No data to insert"); - else - return; + return; } query_interrupt_handler.start(); diff --git a/src/Client/ClientBaseHelpers.cpp b/src/Client/ClientBaseHelpers.cpp index c47e888d5e1..156c0c87fb6 100644 --- a/src/Client/ClientBaseHelpers.cpp +++ b/src/Client/ClientBaseHelpers.cpp @@ -88,7 +88,7 @@ bool isChineseNewYearMode(const String & local_tz) /// Let's celebrate until Lantern Festival if (d <= days && d + 25 >= days) return true; - else if (d > days) + if (d > days) return false; } return false; diff --git a/src/Client/HedgedConnections.cpp b/src/Client/HedgedConnections.cpp index b932156b2d8..c30ca0eb9d4 100644 --- a/src/Client/HedgedConnections.cpp +++ b/src/Client/HedgedConnections.cpp @@ -405,7 +405,7 @@ bool HedgedConnections::resumePacketReceiver(const HedgedConnections::ReplicaLoc last_received_packet = replica_state.packet_receiver->getPacket(); return true; } - else if (replica_state.packet_receiver->isTimeoutExpired()) + if (replica_state.packet_receiver->isTimeoutExpired()) { const String & description = replica_state.connection->getDescription(); finishProcessReplica(replica_state, true); diff --git a/src/Client/LineReader.cpp b/src/Client/LineReader.cpp index 487ef232fdc..e077343ada3 100644 --- a/src/Client/LineReader.cpp +++ b/src/Client/LineReader.cpp @@ -169,8 +169,7 @@ String LineReader::readLine(const String & first_prompt, const String & second_p { if (!line.empty() && !multiline && !hasInputData()) break; - else - continue; + continue; } const char * has_extender = nullptr; diff --git a/src/Client/LocalConnection.cpp b/src/Client/LocalConnection.cpp index f81eb4db959..b4c929155bc 100644 --- a/src/Client/LocalConnection.cpp +++ b/src/Client/LocalConnection.cpp @@ -520,7 +520,7 @@ bool LocalConnection::pollImpl() { return true; } - else if (block && !state->io.null_format) + if (block && !state->io.null_format) { state->block.emplace(block); } diff --git a/src/Client/Suggest.cpp b/src/Client/Suggest.cpp index 657a88c00c8..bda252b157b 100644 --- a/src/Client/Suggest.cpp +++ b/src/Client/Suggest.cpp @@ -113,7 +113,7 @@ void Suggest::load(ContextPtr context, const ConnectionParameters & connection_p last_error = e.code(); if (e.code() == ErrorCodes::DEADLOCK_AVOIDED) continue; - else if (e.code() != ErrorCodes::USER_SESSION_LIMIT_EXCEEDED) + if (e.code() != ErrorCodes::USER_SESSION_LIMIT_EXCEEDED) { /// We should not use std::cerr here, because this method works concurrently with the main thread. /// WriteBufferFromFileDescriptor will write directly to the file descriptor, avoiding data race on std::cerr. diff --git a/src/Client/TestHint.cpp b/src/Client/TestHint.cpp index 74c65009a73..c6d8eaae6f9 100644 --- a/src/Client/TestHint.cpp +++ b/src/Client/TestHint.cpp @@ -78,8 +78,7 @@ bool TestHint::needRetry(const std::unique_ptr & server_exception, si if (retry_until) return !hasExpectedServerError(error); /// retry until we get the expected error - else - return hasExpectedServerError(error); /// retry while we have the expected error + return hasExpectedServerError(error); /// retry while we have the expected error } void TestHint::parse(Lexer & comment_lexer, bool is_leading_hint) diff --git a/src/Client/TestHint.h b/src/Client/TestHint.h index bbe7873c08b..a6d93275c77 100644 --- a/src/Client/TestHint.h +++ b/src/Client/TestHint.h @@ -122,9 +122,8 @@ struct fmt::formatter { if (ErrorVector.empty()) return fmt::format_to(ctx.out(), "{}", 0); - else if (ErrorVector.size() == 1) + if (ErrorVector.size() == 1) return fmt::format_to(ctx.out(), "{}", ErrorVector[0]); - else - return fmt::format_to(ctx.out(), "[{}]", fmt::join(ErrorVector, ", ")); + return fmt::format_to(ctx.out(), "[{}]", fmt::join(ErrorVector, ", ")); } }; diff --git a/src/Columns/ColumnAggregateFunction.cpp b/src/Columns/ColumnAggregateFunction.cpp index d3363d91a46..69bea288779 100644 --- a/src/Columns/ColumnAggregateFunction.cpp +++ b/src/Columns/ColumnAggregateFunction.cpp @@ -746,18 +746,16 @@ MutableColumnPtr ColumnAggregateFunction::cloneResized(size_t size) const res_data.assign(data.begin(), data.begin() + size); return res; } - else - { - /// Create a new column to return. - MutableColumnPtr cloned_col = cloneEmpty(); - auto * res = typeid_cast(cloned_col.get()); - res->insertRangeFrom(*this, 0, from_size); - for (size_t i = from_size; i < size; ++i) - res->insertDefault(); + /// Create a new column to return. + MutableColumnPtr cloned_col = cloneEmpty(); + auto * res = typeid_cast(cloned_col.get()); - return cloned_col; - } + res->insertRangeFrom(*this, 0, from_size); + for (size_t i = from_size; i < size; ++i) + res->insertDefault(); + + return cloned_col; } } diff --git a/src/Columns/ColumnConst.cpp b/src/Columns/ColumnConst.cpp index 84427e7be2b..a57f4e47cfd 100644 --- a/src/Columns/ColumnConst.cpp +++ b/src/Columns/ColumnConst.cpp @@ -75,7 +75,7 @@ void ColumnConst::expand(const Filter & mask, bool inverted) if (bytes_count < s) throw Exception(ErrorCodes::LOGICAL_ERROR, "Not enough bytes in mask"); - else if (bytes_count > s) + if (bytes_count > s) throw Exception(ErrorCodes::LOGICAL_ERROR, "Too many bytes in mask"); s = mask.size(); diff --git a/src/Columns/ColumnDynamic.cpp b/src/Columns/ColumnDynamic.cpp index 5a837a62761..4c7c9b53654 100644 --- a/src/Columns/ColumnDynamic.cpp +++ b/src/Columns/ColumnDynamic.cpp @@ -854,9 +854,9 @@ int ColumnDynamic::doCompareAt(size_t n, size_t m, const IColumn & rhs, int nan_ /// Check if we have NULLs and return result based on nan_direction_hint. if (left_discr == ColumnVariant::NULL_DISCRIMINATOR && right_discr == ColumnVariant::NULL_DISCRIMINATOR) return 0; - else if (left_discr == ColumnVariant::NULL_DISCRIMINATOR) + if (left_discr == ColumnVariant::NULL_DISCRIMINATOR) return nan_direction_hint; - else if (right_discr == ColumnVariant::NULL_DISCRIMINATOR) + if (right_discr == ColumnVariant::NULL_DISCRIMINATOR) return -nan_direction_hint; /// Check if both values are in shared variant. @@ -891,7 +891,7 @@ int ColumnDynamic::doCompareAt(size_t n, size_t m, const IColumn & rhs, int nan_ return tmp_column->compareAt(0, 1, *tmp_column, nan_direction_hint); } /// Check if only left value is in shared data. - else if (left_discr == left_shared_variant_discr) + if (left_discr == left_shared_variant_discr) { /// Extract left type name from the value. auto left_value = getSharedVariant().getDataAt(left_variant.offsetAt(n)); @@ -908,10 +908,11 @@ int ColumnDynamic::doCompareAt(size_t n, size_t m, const IColumn & rhs, int nan_ /// create temporary column, insert the value into it and compare. auto tmp_column = left_data_type->createColumn(); left_data_type->getDefaultSerialization()->deserializeBinary(*tmp_column, buf_left, getFormatSettings()); - return tmp_column->compareAt(0, right_variant.offsetAt(m), right_variant.getVariantByGlobalDiscriminator(right_discr), nan_direction_hint); + return tmp_column->compareAt( + 0, right_variant.offsetAt(m), right_variant.getVariantByGlobalDiscriminator(right_discr), nan_direction_hint); } /// Check if only right value is in shared data. - else if (right_discr == right_shared_variant_discr) + if (right_discr == right_shared_variant_discr) { /// Extract right type name from the value. auto right_value = right_dynamic.getSharedVariant().getDataAt(right_variant.offsetAt(m)); @@ -928,18 +929,22 @@ int ColumnDynamic::doCompareAt(size_t n, size_t m, const IColumn & rhs, int nan_ /// create temporary column, insert the value into it and compare. auto tmp_column = right_data_type->createColumn(); right_data_type->getDefaultSerialization()->deserializeBinary(*tmp_column, buf_right, getFormatSettings()); - return left_variant.getVariantByGlobalDiscriminator(left_discr).compareAt(left_variant.offsetAt(n), 0, *tmp_column, nan_direction_hint); + return left_variant.getVariantByGlobalDiscriminator(left_discr) + .compareAt(left_variant.offsetAt(n), 0, *tmp_column, nan_direction_hint); } /// Otherwise both values are regular variants. - else - { - /// If rows have different types, we compare type names. - if (variant_info.variant_names[left_discr] != right_dynamic.variant_info.variant_names[right_discr]) - return variant_info.variant_names[left_discr] < right_dynamic.variant_info.variant_names[right_discr] ? -1 : 1; - /// If rows have the same types, compare actual values from corresponding variants. - return left_variant.getVariantByGlobalDiscriminator(left_discr).compareAt(left_variant.offsetAt(n), right_variant.offsetAt(m), right_variant.getVariantByGlobalDiscriminator(right_discr), nan_direction_hint); - } + /// If rows have different types, we compare type names. + if (variant_info.variant_names[left_discr] != right_dynamic.variant_info.variant_names[right_discr]) + return variant_info.variant_names[left_discr] < right_dynamic.variant_info.variant_names[right_discr] ? -1 : 1; + + /// If rows have the same types, compare actual values from corresponding variants. + return left_variant.getVariantByGlobalDiscriminator(left_discr) + .compareAt( + left_variant.offsetAt(n), + right_variant.offsetAt(m), + right_variant.getVariantByGlobalDiscriminator(right_discr), + nan_direction_hint); } struct ColumnDynamic::ComparatorBase diff --git a/src/Columns/ColumnLowCardinality.cpp b/src/Columns/ColumnLowCardinality.cpp index a977046b07f..8f94416459c 100644 --- a/src/Columns/ColumnLowCardinality.cpp +++ b/src/Columns/ColumnLowCardinality.cpp @@ -117,15 +117,13 @@ namespace { if (auto * data_uint8 = getIndexesData(column)) return mapUniqueIndexImpl(*data_uint8); - else if (auto * data_uint16 = getIndexesData(column)) + if (auto * data_uint16 = getIndexesData(column)) return mapUniqueIndexImpl(*data_uint16); - else if (auto * data_uint32 = getIndexesData(column)) + if (auto * data_uint32 = getIndexesData(column)) return mapUniqueIndexImpl(*data_uint32); - else if (auto * data_uint64 = getIndexesData(column)) + if (auto * data_uint64 = getIndexesData(column)) return mapUniqueIndexImpl(*data_uint64); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Indexes column for getUniqueIndex must be ColumnUInt, got {}", - column.getName()); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Indexes column for getUniqueIndex must be ColumnUInt, got {}", column.getName()); } } @@ -441,8 +439,7 @@ void ColumnLowCardinality::updatePermutation(IColumn::PermutationSortDirection d if (ascending) return ret < 0; - else - return ret > 0; + return ret > 0; }; auto equal_comparator = [this, nan_direction_hint](size_t lhs, size_t rhs) @@ -478,8 +475,7 @@ void ColumnLowCardinality::updatePermutationWithCollation(const Collator & colla if (ascending) return ret < 0; - else - return ret > 0; + return ret > 0; }; auto equal_comparator = [this, &collator, nan_direction_hint](size_t lhs, size_t rhs) diff --git a/src/Columns/ColumnNullable.cpp b/src/Columns/ColumnNullable.cpp index ec375ea5a8d..c604b2939b2 100644 --- a/src/Columns/ColumnNullable.cpp +++ b/src/Columns/ColumnNullable.cpp @@ -118,32 +118,28 @@ Float64 ColumnNullable::getFloat64(size_t n) const { if (isNullAt(n)) throw Exception(ErrorCodes::BAD_ARGUMENTS, "The value of {} at {} is NULL while calling method getFloat64", getName(), n); - else - return getNestedColumn().getFloat64(n); + return getNestedColumn().getFloat64(n); } Float32 ColumnNullable::getFloat32(size_t n) const { if (isNullAt(n)) throw Exception(ErrorCodes::BAD_ARGUMENTS, "The value of {} at {} is NULL while calling method getFloat32", getName(), n); - else - return getNestedColumn().getFloat32(n); + return getNestedColumn().getFloat32(n); } UInt64 ColumnNullable::getUInt(size_t n) const { if (isNullAt(n)) throw Exception(ErrorCodes::BAD_ARGUMENTS, "The value of {} at {} is NULL while calling method getUInt", getName(), n); - else - return getNestedColumn().getUInt(n); + return getNestedColumn().getUInt(n); } Int64 ColumnNullable::getInt(size_t n) const { if (isNullAt(n)) throw Exception(ErrorCodes::BAD_ARGUMENTS, "The value of {} at {} is NULL while calling method getInt", getName(), n); - else - return getNestedColumn().getInt(n); + return getNestedColumn().getInt(n); } void ColumnNullable::insertData(const char * pos, size_t length) @@ -399,8 +395,7 @@ int ColumnNullable::compareAtImpl(size_t n, size_t m, const IColumn & rhs_, int { if (lval_is_null && rval_is_null) return 0; - else - return lval_is_null ? null_direction_hint : -null_direction_hint; + return lval_is_null ? null_direction_hint : -null_direction_hint; } const IColumn & nested_rhs = nullable_rhs.getNestedColumn(); diff --git a/src/Columns/ColumnTuple.cpp b/src/Columns/ColumnTuple.cpp index 0e26ada64ad..1cb6d0b60d8 100644 --- a/src/Columns/ColumnTuple.cpp +++ b/src/Columns/ColumnTuple.cpp @@ -520,7 +520,7 @@ struct ColumnTuple::Less res = column->compareAt(a, b, *column, nan_direction_hint); if (res < 0) return positive; - else if (res > 0) + if (res > 0) return !positive; } return false; @@ -703,8 +703,7 @@ bool ColumnTuple::structureEquals(const IColumn & rhs) const return true; } - else - return false; + return false; } bool ColumnTuple::isCollationSupported() const diff --git a/src/Columns/ColumnUnique.h b/src/Columns/ColumnUnique.h index 8a66f4e02ed..ffa7c311e9e 100644 --- a/src/Columns/ColumnUnique.h +++ b/src/Columns/ColumnUnique.h @@ -510,8 +510,7 @@ int ColumnUnique::doCompareAt(size_t n, size_t m, const IColumn & rh { if (lval_is_null && rval_is_null) return 0; - else - return lval_is_null ? nan_direction_hint : -nan_direction_hint; + return lval_is_null ? nan_direction_hint : -nan_direction_hint; } } diff --git a/src/Columns/ColumnVariant.cpp b/src/Columns/ColumnVariant.cpp index c2b51a5fcf1..ea4a16ca611 100644 --- a/src/Columns/ColumnVariant.cpp +++ b/src/Columns/ColumnVariant.cpp @@ -1207,9 +1207,9 @@ int ColumnVariant::doCompareAt(size_t n, size_t m, const IColumn & rhs, int nan_ /// Check if we have NULLs and return result based on nan_direction_hint. if (left_discr == NULL_DISCRIMINATOR && right_discr == NULL_DISCRIMINATOR) return 0; - else if (left_discr == NULL_DISCRIMINATOR) + if (left_discr == NULL_DISCRIMINATOR) return nan_direction_hint; - else if (right_discr == NULL_DISCRIMINATOR) + if (right_discr == NULL_DISCRIMINATOR) return -nan_direction_hint; /// If rows have different discriminators, row with least discriminator is considered the least. diff --git a/src/Columns/ColumnVector.cpp b/src/Columns/ColumnVector.cpp index c474efe35bd..dc4941988e9 100644 --- a/src/Columns/ColumnVector.cpp +++ b/src/Columns/ColumnVector.cpp @@ -543,8 +543,7 @@ uint8_t prefixToCopy(UInt64 mask) const UInt64 leading_zeroes = __builtin_clzll(mask); if (mask == ((static_cast(-1) << leading_zeroes) >> leading_zeroes)) return 64 - leading_zeroes; - else - return 0xFF; + return 0xFF; } uint8_t suffixToCopy(UInt64 mask) diff --git a/src/Columns/ColumnsCommon.h b/src/Columns/ColumnsCommon.h index 6aedd272070..99f1d2da47e 100644 --- a/src/Columns/ColumnsCommon.h +++ b/src/Columns/ColumnsCommon.h @@ -117,15 +117,14 @@ ColumnPtr selectIndexImpl(const Column & column, const IColumn & indexes, size_t if (const auto * data_uint8 = detail::getIndexesData(indexes)) return column.template indexImpl(*data_uint8, limit); - else if (const auto * data_uint16 = detail::getIndexesData(indexes)) + if (const auto * data_uint16 = detail::getIndexesData(indexes)) return column.template indexImpl(*data_uint16, limit); - else if (const auto * data_uint32 = detail::getIndexesData(indexes)) + if (const auto * data_uint32 = detail::getIndexesData(indexes)) return column.template indexImpl(*data_uint32, limit); - else if (const auto * data_uint64 = detail::getIndexesData(indexes)) + if (const auto * data_uint64 = detail::getIndexesData(indexes)) return column.template indexImpl(*data_uint64, limit); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Indexes column for IColumn::select must be ColumnUInt, got {}", - indexes.getName()); + + throw Exception(ErrorCodes::LOGICAL_ERROR, "Indexes column for IColumn::select must be ColumnUInt, got {}", indexes.getName()); } size_t getLimitForPermutation(size_t column_size, size_t perm_size, size_t limit); diff --git a/src/Columns/IColumn.cpp b/src/Columns/IColumn.cpp index 15e29d1422a..c9a0514af4e 100644 --- a/src/Columns/IColumn.cpp +++ b/src/Columns/IColumn.cpp @@ -353,10 +353,8 @@ IColumnHelper::serializeValueIntoArenaWithNull(size_t n, Arena self.serializeValueIntoMemory(n, memory + 1); return {memory, sz}; } - else - { - return self.serializeValueIntoArena(n, arena, begin); - } + + return self.serializeValueIntoArena(n, arena, begin); } template diff --git a/src/Common/Allocator.cpp b/src/Common/Allocator.cpp index 1b43e746c69..b861252ce11 100644 --- a/src/Common/Allocator.cpp +++ b/src/Common/Allocator.cpp @@ -82,10 +82,8 @@ void * allocNoTrack(size_t size, size_t alignment) return ptr; } - else - { - ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); - } + + ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); } #endif if (alignment <= MALLOC_MIN_ALIGNMENT) @@ -204,11 +202,9 @@ void * Allocator::realloc(void * buf, size_t old_size, ProfileEvents::increment(ProfileEvents::GWPAsanAllocateSuccess); return ptr; } - else - { - [[maybe_unused]] auto trace_free = CurrentMemoryTracker::free(new_size); - ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); - } + + [[maybe_unused]] auto trace_free = CurrentMemoryTracker::free(new_size); + ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); } if (unlikely(GWPAsan::GuardedAlloc.pointerIsMine(buf))) diff --git a/src/Common/ArenaAllocator.h b/src/Common/ArenaAllocator.h index 36d1772daea..eb82ff69369 100644 --- a/src/Common/ArenaAllocator.h +++ b/src/Common/ArenaAllocator.h @@ -26,10 +26,8 @@ public: arena->allocContinue(new_size - old_size, data); return reinterpret_cast(const_cast(data)); } - else - { - return arena->realloc(data, old_size, new_size); - } + + return arena->realloc(data, old_size, new_size); } static void free(void * /*buf*/, size_t /*size*/) @@ -64,10 +62,8 @@ public: arena->allocContinue(new_size - old_size, data, alignment); return reinterpret_cast(const_cast(data)); } - else - { - return arena->alignedRealloc(data, old_size, new_size, alignment); - } + + return arena->alignedRealloc(data, old_size, new_size, alignment); } static void free(void * /*buf*/, size_t /*size*/) diff --git a/src/Common/AsyncLoader.cpp b/src/Common/AsyncLoader.cpp index cc6358adb46..01a08053a03 100644 --- a/src/Common/AsyncLoader.cpp +++ b/src/Common/AsyncLoader.cpp @@ -579,8 +579,7 @@ String AsyncLoader::checkCycle(const LoadJobPtr & job, LoadJobSet & left, LoadJo { if (!visited.contains(job)) // Check for cycle end throw Exception(ErrorCodes::ASYNC_LOAD_CYCLE, "Load job dependency cycle detected: {} -> {}", job->name, chain); - else - return fmt::format("{} -> {}", job->name, chain); // chain is not a cycle yet -- continue building + return fmt::format("{} -> {}", job->name, chain); // chain is not a cycle yet -- continue building } } left.erase(job); diff --git a/src/Common/AsynchronousMetrics.cpp b/src/Common/AsynchronousMetrics.cpp index a92d321f8aa..f419a23b209 100644 --- a/src/Common/AsynchronousMetrics.cpp +++ b/src/Common/AsynchronousMetrics.cpp @@ -141,8 +141,7 @@ void AsynchronousMetrics::openSensors() TSA_REQUIRES(data_mutex) /// Sometimes indices are from zero sometimes from one. if (thermal_device_index == 0) continue; - else - break; + break; } file->rewind(); @@ -210,8 +209,7 @@ void AsynchronousMetrics::openEDAC() TSA_REQUIRES(data_mutex) { if (edac_index == 0) continue; - else - break; + break; } edac.emplace_back(); @@ -236,8 +234,7 @@ void AsynchronousMetrics::openSensorsChips() TSA_REQUIRES(data_mutex) { if (hwmon_index == 0) continue; - else - break; + break; } String hwmon_name; @@ -258,8 +255,7 @@ void AsynchronousMetrics::openSensorsChips() TSA_REQUIRES(data_mutex) { if (sensor_index == 0) continue; - else - break; + break; } std::unique_ptr file = openFileIfExists(sensor_value_file); @@ -1007,8 +1003,7 @@ void AsynchronousMetrics::update(TimePoint update_time, bool force_update) { if (auto hz = sysconf(_SC_CLK_TCK); hz != -1) return hz; - else - throw ErrnoException(ErrorCodes::CANNOT_SYSCONF, "Cannot call 'sysconf' to obtain system HZ"); + throw ErrnoException(ErrorCodes::CANNOT_SYSCONF, "Cannot call 'sysconf' to obtain system HZ"); }; const auto cgroup_version_specific_divisor = cgroupcpu_stat ? 1e6 : get_clock_ticks(); const double multiplier = 1.0 / cgroup_version_specific_divisor @@ -1764,8 +1759,7 @@ void AsynchronousMetrics::update(TimePoint update_time, bool force_update) auto it = metric_map.find(name); if (it == metric_map.end()) return { nullptr, nullptr }; - else - return it->second; + return it->second; }; auto rejected_connections_get_metric_name_doc = [](const String & name) -> std::pair @@ -1788,8 +1782,7 @@ void AsynchronousMetrics::update(TimePoint update_time, bool force_update) auto it = metric_map.find(name); if (it == metric_map.end()) return { nullptr, nullptr }; - else - return it->second; + return it->second; }; const auto server_metrics = protocol_server_metrics_func(); diff --git a/src/Common/BufferAllocationPolicy.cpp b/src/Common/BufferAllocationPolicy.cpp index 9f9665be9b9..035b280fe3f 100644 --- a/src/Common/BufferAllocationPolicy.cpp +++ b/src/Common/BufferAllocationPolicy.cpp @@ -95,8 +95,7 @@ BufferAllocationPolicyPtr BufferAllocationPolicy::create(BufferAllocationPolicy: { if (settings_.strict_size > 0) return std::make_unique(settings_); - else - return std::make_unique(settings_); + return std::make_unique(settings_); } } diff --git a/src/Common/COW.h b/src/Common/COW.h index f772acd84e0..ec9cfa6dba8 100644 --- a/src/Common/COW.h +++ b/src/Common/COW.h @@ -169,8 +169,7 @@ protected: { if (this->use_count() > 1) return derived()->clone(); - else - return assumeMutable(); + return assumeMutable(); } public: diff --git a/src/Common/CalendarTimeInterval.cpp b/src/Common/CalendarTimeInterval.cpp index 43b0b030be0..101c0a6a813 100644 --- a/src/Common/CalendarTimeInterval.cpp +++ b/src/Common/CalendarTimeInterval.cpp @@ -122,13 +122,11 @@ std::chrono::sys_seconds CalendarTimeInterval::floor(std::chrono::system_clock:: if (months) return startOfAbsoluteMonth(toAbsoluteMonth(tp) / months * months); - else - { - constexpr std::chrono::seconds epoch(-3600*24*3); - auto t = std::chrono::sys_seconds(std::chrono::floor(tp)); - /// We want to align with weeks, but 1970-01-01 is a Thursday, so align with 1969-12-29 instead. - return std::chrono::sys_seconds((t.time_since_epoch() - epoch) / seconds * seconds + epoch); - } + + constexpr std::chrono::seconds epoch(-3600 * 24 * 3); + auto t = std::chrono::sys_seconds(std::chrono::floor(tp)); + /// We want to align with weeks, but 1970-01-01 is a Thursday, so align with 1969-12-29 instead. + return std::chrono::sys_seconds((t.time_since_epoch() - epoch) / seconds * seconds + epoch); } bool CalendarTimeInterval::operator==(const CalendarTimeInterval & rhs) const diff --git a/src/Common/CancelToken.cpp b/src/Common/CancelToken.cpp index 077d60c7efa..2b3d027d89d 100644 --- a/src/Common/CancelToken.cpp +++ b/src/Common/CancelToken.cpp @@ -121,11 +121,9 @@ bool CancelToken::wait(UInt32 * address, UInt32 value) { if (s == canceled) break; // Signaled; futex "release" has been done by the signaling thread - else - { - s = state.load(); - continue; // To avoid race (may lead to futex destruction) we have to wait for signaling thread to finish - } + + s = state.load(); + continue; // To avoid race (may lead to futex destruction) we have to wait for signaling thread to finish } if (state.compare_exchange_strong(s, 0)) return true; // There was no cancellation; futex "released" @@ -143,8 +141,7 @@ void CancelToken::raise() throw DB::Exception::createRuntime( std::exchange(exception_code, 0), std::exchange(exception_message, {})); - else - throw DB::Exception(ErrorCodes::THREAD_WAS_CANCELED, "Thread was canceled"); + throw DB::Exception(ErrorCodes::THREAD_WAS_CANCELED, "Thread was canceled"); } void CancelToken::notifyOne(UInt32 * address) diff --git a/src/Common/CaresPTRResolver.cpp b/src/Common/CaresPTRResolver.cpp index df456c9cfbd..9772ef0756a 100644 --- a/src/Common/CaresPTRResolver.cpp +++ b/src/Common/CaresPTRResolver.cpp @@ -153,7 +153,7 @@ namespace DB { continue; } - else if (poll_error) + if (poll_error) { return false; } diff --git a/src/Common/CombinedCardinalityEstimator.h b/src/Common/CombinedCardinalityEstimator.h index 2c3e1e07745..607a5764b64 100644 --- a/src/Common/CombinedCardinalityEstimator.h +++ b/src/Common/CombinedCardinalityEstimator.h @@ -121,12 +121,11 @@ public: if (container_type == details::ContainerType::SMALL) return small.size(); - else if (container_type == details::ContainerType::MEDIUM) + if (container_type == details::ContainerType::MEDIUM) return getContainer().size(); - else if (container_type == details::ContainerType::LARGE) + if (container_type == details::ContainerType::LARGE) return getContainer().size(); - else - throw Poco::Exception("Internal error", ErrorCodes::LOGICAL_ERROR); + throw Poco::Exception("Internal error", ErrorCodes::LOGICAL_ERROR); } void merge(const Self & rhs) diff --git a/src/Common/CompactArray.h b/src/Common/CompactArray.h index 7b2bd658d2e..39e2609e37d 100644 --- a/src/Common/CompactArray.h +++ b/src/Common/CompactArray.h @@ -36,8 +36,7 @@ public: if (locus.index_l == locus.index_r) return locus.read(bitset[locus.index_l]); - else - return locus.read(bitset[locus.index_l], bitset[locus.index_r]); + return locus.read(bitset[locus.index_l], bitset[locus.index_r]); } Locus ALWAYS_INLINE operator[](BucketIndex bucket_index) @@ -123,8 +122,7 @@ public: if (fits_in_byte) return std::make_pair(current_bucket_index - 1, locus.read(value_l)); - else - return std::make_pair(current_bucket_index - 1, locus.read(value_l, value_r)); + return std::make_pair(current_bucket_index - 1, locus.read(value_l, value_r)); } private: @@ -163,8 +161,7 @@ public: { if (content_l == content_r) return read(*content_l); - else - return read(*content_l, *content_r); + return read(*content_l, *content_r); } Locus ALWAYS_INLINE & operator=(UInt8 content) diff --git a/src/Common/ConcurrencyControl.cpp b/src/Common/ConcurrencyControl.cpp index 0893cfce955..8bc38af7aa5 100644 --- a/src/Common/ConcurrencyControl.cpp +++ b/src/Common/ConcurrencyControl.cpp @@ -108,8 +108,7 @@ ConcurrencyControl::~ConcurrencyControl() if (granted < max) return SlotAllocationPtr(new Allocation(*this, max, granted, waiters.insert(cur_waiter, nullptr /* pointer is set by Allocation ctor */))); - else - return SlotAllocationPtr(new Allocation(*this, max, granted)); + return SlotAllocationPtr(new Allocation(*this, max, granted)); } void ConcurrencyControl::setMaxConcurrency(SlotCount value) @@ -172,8 +171,7 @@ SlotCount ConcurrencyControl::available(std::unique_lock &) const { if (cur_concurrency < max_concurrency) return max_concurrency - cur_concurrency; - else - return 0; + return 0; } } diff --git a/src/Common/Config/AbstractConfigurationComparison.cpp b/src/Common/Config/AbstractConfigurationComparison.cpp index 80c837ed43b..73f305ce669 100644 --- a/src/Common/Config/AbstractConfigurationComparison.cpp +++ b/src/Common/Config/AbstractConfigurationComparison.cpp @@ -55,25 +55,21 @@ namespace { return right.hasProperty(right_key) && (left.getRawString(left_key) == right.getRawString(right_key)); } - else - { - return !right.hasProperty(right_key); - } - } - else - { - /// Go through all the subkeys and compare corresponding parts of the configurations. - std::unordered_set left_subkeys_set{left_subkeys.begin(), left_subkeys.end()}; - for (const auto & subkey : right_subkeys) - { - if (!left_subkeys_set.contains(subkey)) - return false; - if (!isSameConfigurationImpl(left, concatKeyAndSubKey(left_key, subkey), right, concatKeyAndSubKey(right_key, subkey), nullptr)) - return false; - } - return true; + return !right.hasProperty(right_key); } + + /// Go through all the subkeys and compare corresponding parts of the configurations. + std::unordered_set left_subkeys_set{left_subkeys.begin(), left_subkeys.end()}; + for (const auto & subkey : right_subkeys) + { + if (!left_subkeys_set.contains(subkey)) + return false; + + if (!isSameConfigurationImpl(left, concatKeyAndSubKey(left_key, subkey), right, concatKeyAndSubKey(right_key, subkey), nullptr)) + return false; + } + return true; } } diff --git a/src/Common/Config/ConfigProcessor.cpp b/src/Common/Config/ConfigProcessor.cpp index c4b4a1d5e7e..4e60eadd835 100644 --- a/src/Common/Config/ConfigProcessor.cpp +++ b/src/Common/Config/ConfigProcessor.cpp @@ -635,39 +635,37 @@ XMLDocumentPtr ConfigProcessor::parseConfig(const std::string & config_path) if (extension == ".xml") return dom_parser.parse(config_path); - else if (extension == ".yaml" || extension == ".yml") + if (extension == ".yaml" || extension == ".yml") return YAMLParser::parse(config_path); - else + + /// Suppose non regular file parsed as XML, such as pipe: /dev/fd/X (regardless it has .xml extension or not) + if (!fs::is_regular_file(config_path)) + return dom_parser.parse(config_path); + + /// If the regular file begins with < it might be XML, otherwise it might be YAML. + bool maybe_xml = false; { - /// Suppose non regular file parsed as XML, such as pipe: /dev/fd/X (regardless it has .xml extension or not) - if (!fs::is_regular_file(config_path)) - return dom_parser.parse(config_path); + std::ifstream file(config_path); + if (!file.is_open()) + throw Exception(ErrorCodes::CANNOT_LOAD_CONFIG, "Unknown format of '{}' config", config_path); - /// If the regular file begins with < it might be XML, otherwise it might be YAML. - bool maybe_xml = false; + std::string line; + while (std::getline(file, line)) { - std::ifstream file(config_path); - if (!file.is_open()) - throw Exception(ErrorCodes::CANNOT_LOAD_CONFIG, "Unknown format of '{}' config", config_path); + const size_t pos = firstNonWhitespacePos(line); - std::string line; - while (std::getline(file, line)) + if (pos < line.size() && '<' == line[pos]) { - const size_t pos = firstNonWhitespacePos(line); - - if (pos < line.size() && '<' == line[pos]) - { - maybe_xml = true; - break; - } - else if (pos != std::string::npos) - break; + maybe_xml = true; + break; } + if (pos != std::string::npos) + break; } - if (maybe_xml) - return dom_parser.parse(config_path); - return YAMLParser::parse(config_path); } + if (maybe_xml) + return dom_parser.parse(config_path); + return YAMLParser::parse(config_path); } XMLDocumentPtr ConfigProcessor::processConfig( diff --git a/src/Common/CounterInFile.h b/src/Common/CounterInFile.h index 2d4ad36f7f2..3e58b704170 100644 --- a/src/Common/CounterInFile.h +++ b/src/Common/CounterInFile.h @@ -89,8 +89,7 @@ public: /// A more understandable error message. if (e.code() == DB::ErrorCodes::CANNOT_READ_ALL_DATA || e.code() == DB::ErrorCodes::ATTEMPT_TO_READ_AFTER_EOF) throw DB::Exception(e.code(), "File {} is empty. You must fill it manually with appropriate value.", path); - else - throw; + throw; } } else diff --git a/src/Common/CurrentMemoryTracker.cpp b/src/Common/CurrentMemoryTracker.cpp index 02c7dc6e224..c159c25f793 100644 --- a/src/Common/CurrentMemoryTracker.cpp +++ b/src/Common/CurrentMemoryTracker.cpp @@ -59,12 +59,10 @@ AllocationTrace CurrentMemoryTracker::allocImpl(Int64 size, bool throw_if_memory current_thread->untracked_memory = 0; return res; } - else - { - /// Update after successful allocations, - /// since failed allocations should not be take into account. - current_thread->untracked_memory = will_be; - } + + /// Update after successful allocations, + /// since failed allocations should not be take into account. + current_thread->untracked_memory = will_be; } /// total_memory_tracker only, ignore untracked_memory else diff --git a/src/Common/DNSResolver.cpp b/src/Common/DNSResolver.cpp index 68a8fa7d74c..5a18ef893e0 100644 --- a/src/Common/DNSResolver.cpp +++ b/src/Common/DNSResolver.cpp @@ -147,10 +147,8 @@ std::unordered_set reverseResolveImpl(const Poco::Net::IPAddress & addre if (address.family() == Poco::Net::IPAddress::Family::IPv4) { return ptr_resolver->resolve(address.toString()); - } else - { - return ptr_resolver->resolve_v6(address.toString()); } + return ptr_resolver->resolve_v6(address.toString()); } std::unordered_set reverseResolveWithCache( diff --git a/src/Common/DateLUTImpl.cpp b/src/Common/DateLUTImpl.cpp index c87d44a4b95..355d39780f2 100644 --- a/src/Common/DateLUTImpl.cpp +++ b/src/Common/DateLUTImpl.cpp @@ -267,11 +267,9 @@ namespace cctz_extension size -= offset; return 0; } - else - { - errno = EINVAL; - return -1; - } + + errno = EINVAL; + return -1; } private: const char * data; diff --git a/src/Common/DateLUTImpl.h b/src/Common/DateLUTImpl.h index 22b4b630ce5..f1a937d1c65 100644 --- a/src/Common/DateLUTImpl.h +++ b/src/Common/DateLUTImpl.h @@ -883,14 +883,12 @@ public: { return toFirstDayNumOfWeek(v); } + + const auto day_of_week = toDayOfWeek(v); + if constexpr (std::is_unsigned_v || std::is_same_v) + return (day_of_week != 7) ? DayNum(saturateMinus(v, day_of_week)) : toDayNum(v); else - { - const auto day_of_week = toDayOfWeek(v); - if constexpr (std::is_unsigned_v || std::is_same_v) - return (day_of_week != 7) ? DayNum(saturateMinus(v, day_of_week)) : toDayNum(v); - else - return (day_of_week != 7) ? ExtendedDayNum(v - day_of_week) : toDayNum(v); - } + return (day_of_week != 7) ? ExtendedDayNum(v - day_of_week) : toDayNum(v); } /// Get last day of week with week_mode, return Saturday or Sunday @@ -902,15 +900,13 @@ public: { return toLastDayNumOfWeek(v); } + + const auto day_of_week = toDayOfWeek(v); + v += 6; + if constexpr (std::is_unsigned_v || std::is_same_v) + return (day_of_week != 7) ? DayNum(saturateMinus(v, day_of_week)) : toDayNum(v); else - { - const auto day_of_week = toDayOfWeek(v); - v += 6; - if constexpr (std::is_unsigned_v || std::is_same_v) - return (day_of_week != 7) ? DayNum(saturateMinus(v, day_of_week)) : toDayNum(v); - else - return (day_of_week != 7) ? ExtendedDayNum(v - day_of_week) : toDayNum(v); - } + return (day_of_week != 7) ? ExtendedDayNum(v - day_of_week) : toDayNum(v); } /// Check and change mode to effective. @@ -937,8 +933,7 @@ public: const LUTIndex i = toLUTIndex(v); if (!sunday_first_day_of_week) return toDayOfWeek(i) - 1; - else - return toDayOfWeek(i + 1) - 1; + return toDayOfWeek(i + 1) - 1; } /// Calculate days in one year. @@ -1367,14 +1362,12 @@ public: return makeLUTIndex(year, month, day_of_month); } - else - { - auto year = values.year - (12 - month) / 12; - month = 12 - (-month % 12); - auto day_of_month = saturateDayOfMonth(year, month, values.day_of_month); - return makeLUTIndex(year, month, day_of_month); - } + auto year = values.year - (12 - month) / 12; + month = 12 - (-month % 12); + auto day_of_month = saturateDayOfMonth(year, month, values.day_of_month); + + return makeLUTIndex(year, month, day_of_month); } /// If resulting month has less days than source month, then saturation can happen. diff --git a/src/Common/Dwarf.cpp b/src/Common/Dwarf.cpp index 37d0d51db91..1b31903cde7 100644 --- a/src/Common/Dwarf.cpp +++ b/src/Common/Dwarf.cpp @@ -1480,7 +1480,7 @@ bool Dwarf::findAddress( findLocation(address, mode, unit, locationInfo, inline_frames, /*assume_in_cu_range*/ true); return locationInfo.has_file_and_line; } - else if (mode == LocationInfoMode::FAST) + if (mode == LocationInfoMode::FAST) { // NOTE: Clang (when using -gdwarf-aranges) doesn't generate entries // in .debug_aranges for some functions, but always generates @@ -1488,11 +1488,9 @@ bool Dwarf::findAddress( // it only if such behavior is requested via LocationInfoMode. return false; } - else - { - SAFE_CHECK(mode == LocationInfoMode::FULL || mode == LocationInfoMode::FULL_WITH_INLINE, "unexpected mode"); - // Fall back to the linear scan. - } + + SAFE_CHECK(mode == LocationInfoMode::FULL || mode == LocationInfoMode::FULL_WITH_INLINE, "unexpected mode"); + // Fall back to the linear scan. } // Slow path (linear scan): Iterate over all .debug_info entries @@ -1947,33 +1945,31 @@ Dwarf::LineNumberVM::FileName Dwarf::LineNumberVM::getFileName(uint64_t index) c return fn; } - else + + FileName fn; + SAFE_CHECK(index < v5_.fileNamesCount, "invalid file index"); + std::string_view file_names = v5_.fileNames; + for (uint64_t i = 0; i < v5_.fileNamesCount; i++) { - FileName fn; - SAFE_CHECK(index < v5_.fileNamesCount, "invalid file index"); - std::string_view file_names = v5_.fileNames; - for (uint64_t i = 0; i < v5_.fileNamesCount; i++) + std::string_view format = v5_.fileNameEntryFormat; + for (uint8_t f = 0; f < v5_.fileNameEntryFormatCount; f++) { - std::string_view format = v5_.fileNameEntryFormat; - for (uint8_t f = 0; f < v5_.fileNameEntryFormatCount; f++) + auto attr = readLineNumberAttribute(is64Bit_, format, file_names, debugStr_, debugLineStr_); + if (i == index) { - auto attr = readLineNumberAttribute(is64Bit_, format, file_names, debugStr_, debugLineStr_); - if (i == index) + switch (attr.content_type_code) // NOLINT(bugprone-switch-missing-default-case) { - switch (attr.content_type_code) // NOLINT(bugprone-switch-missing-default-case) - { - case DW_LNCT_path: - fn.relativeName = std::get(attr.attr_value); - break; - case DW_LNCT_directory_index: - fn.directoryIndex = std::get(attr.attr_value); - break; - } + case DW_LNCT_path: + fn.relativeName = std::get(attr.attr_value); + break; + case DW_LNCT_directory_index: + fn.directoryIndex = std::get(attr.attr_value); + break; } } } - return fn; } + return fn; } std::string_view Dwarf::LineNumberVM::getIncludeDirectory(uint64_t index) const @@ -2004,26 +2000,24 @@ std::string_view Dwarf::LineNumberVM::getIncludeDirectory(uint64_t index) const return dir; } - else + + SAFE_CHECK(index < v5_.directoriesCount, "invalid file index"); + std::string_view directories = v5_.directories; + for (uint64_t i = 0; i < v5_.directoriesCount; i++) { - SAFE_CHECK(index < v5_.directoriesCount, "invalid file index"); - std::string_view directories = v5_.directories; - for (uint64_t i = 0; i < v5_.directoriesCount; i++) + std::string_view format = v5_.directoryEntryFormat; + for (uint8_t f = 0; f < v5_.directoryEntryFormatCount; f++) { - std::string_view format = v5_.directoryEntryFormat; - for (uint8_t f = 0; f < v5_.directoryEntryFormatCount; f++) + auto attr = readLineNumberAttribute(is64Bit_, format, directories, debugStr_, debugLineStr_); + if (i == index && attr.content_type_code == DW_LNCT_path) { - auto attr = readLineNumberAttribute(is64Bit_, format, directories, debugStr_, debugLineStr_); - if (i == index && attr.content_type_code == DW_LNCT_path) - { - return std::get(attr.attr_value); - } + return std::get(attr.attr_value); } } - // This could only happen if DWARF5's directory_entry_format doesn't contain - // a DW_LNCT_path. Highly unlikely, but we shouldn't crash. - return std::string_view(""); } + // This could only happen if DWARF5's directory_entry_format doesn't contain + // a DW_LNCT_path. Highly unlikely, but we shouldn't crash. + return std::string_view(""); } bool Dwarf::LineNumberVM::readFileName(std::string_view & program, FileName & fn) diff --git a/src/Common/Elf.cpp b/src/Common/Elf.cpp index 5599df63948..6007d7a367a 100644 --- a/src/Common/Elf.cpp +++ b/src/Common/Elf.cpp @@ -192,8 +192,7 @@ String Elf::getStoredBinaryHash() const { if (auto section = findSectionByName(".clickhouse.hash")) return {section->begin(), section->end()}; - else - return {}; + return {}; } diff --git a/src/Common/Epoll.cpp b/src/Common/Epoll.cpp index 46cadfd2ac1..4789120309f 100644 --- a/src/Common/Epoll.cpp +++ b/src/Common/Epoll.cpp @@ -81,11 +81,9 @@ size_t Epoll::getManyReady(int max_events, epoll_event * events_out, int timeout } continue; } - else - throw ErrnoException(ErrorCodes::EPOLL_ERROR, "Error in epoll_wait"); + throw ErrnoException(ErrorCodes::EPOLL_ERROR, "Error in epoll_wait"); } - else - break; + break; } return ready_size; diff --git a/src/Common/FailPoint.cpp b/src/Common/FailPoint.cpp index 725c83a94e3..5978dbc18d2 100644 --- a/src/Common/FailPoint.cpp +++ b/src/Common/FailPoint.cpp @@ -184,14 +184,13 @@ void FailPointInjection::disableFailPoint(const String & fail_point_name) void FailPointInjection::wait(const String & fail_point_name) { std::unique_lock lock(mu); - if (auto iter = fail_point_wait_channels.find(fail_point_name); iter == fail_point_wait_channels.end()) + auto iter = fail_point_wait_channels.find(fail_point_name); + if (iter == fail_point_wait_channels.end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Can not find channel for fail point {}", fail_point_name); - else - { - lock.unlock(); - auto ptr = iter->second; - ptr->wait(); - } + + lock.unlock(); + auto ptr = iter->second; + ptr->wait(); } void FailPointInjection::enableFromGlobalConfig(const Poco::Util::AbstractConfiguration & config) diff --git a/src/Common/FieldVisitorConvertToNumber.h b/src/Common/FieldVisitorConvertToNumber.h index 86e03cb5d77..4c3424e0e18 100644 --- a/src/Common/FieldVisitorConvertToNumber.h +++ b/src/Common/FieldVisitorConvertToNumber.h @@ -69,7 +69,7 @@ public: /// Conversion of infinite values to integer is undefined. throw Exception(ErrorCodes::CANNOT_CONVERT_TYPE, "Cannot convert infinite value to integer type"); } - else if (x > Float64(std::numeric_limits::max()) || x < Float64(std::numeric_limits::lowest())) + if (x > Float64(std::numeric_limits::max()) || x < Float64(std::numeric_limits::lowest())) { throw Exception(ErrorCodes::CANNOT_CONVERT_TYPE, "Cannot convert out of range floating point value to integer type"); } diff --git a/src/Common/HashTable/HashTable.h b/src/Common/HashTable/HashTable.h index a600f57b06a..05a257de2e2 100644 --- a/src/Common/HashTable/HashTable.h +++ b/src/Common/HashTable/HashTable.h @@ -1166,10 +1166,8 @@ public: this->clearHasZero(); return true; } - else - { - return false; - } + + return false; } size_t erased_key_position = findCell(x, hash_value, grower.place(hash_value)); diff --git a/src/Common/HashTable/StringHashTable.h b/src/Common/HashTable/StringHashTable.h index 30137d4ca6e..a1b87090fb1 100644 --- a/src/Common/HashTable/StringHashTable.h +++ b/src/Common/HashTable/StringHashTable.h @@ -417,8 +417,7 @@ public: auto it = map.find(key, hash); if (!it) return decltype(&it->getMapped()){}; - else - return &it->getMapped(); + return &it->getMapped(); } }; diff --git a/src/Common/HilbertUtils.h b/src/Common/HilbertUtils.h index f0f8360de90..9a352f875cc 100644 --- a/src/Common/HilbertUtils.h +++ b/src/Common/HilbertUtils.h @@ -127,17 +127,12 @@ inline std::array, 2> createRangeFromCorners(UInt64 x1 std::pair{y_min, y_min + range_size} }; } - else - { - UInt64 x_max = std::max(x1, x2); - UInt64 y_max = std::max(y1, y2); - chassert(x_max >= range_size); - chassert(y_max >= range_size); - return { - std::pair{x_max - range_size, x_max}, - std::pair{y_max - range_size, y_max} - }; - } + + UInt64 x_max = std::max(x1, x2); + UInt64 y_max = std::max(y1, y2); + chassert(x_max >= range_size); + chassert(y_max >= range_size); + return {std::pair{x_max - range_size, x_max}, std::pair{y_max - range_size, y_max}}; } /** Unpack an interval of Hilbert curve to hyperrectangles covered by it across N dimensions. diff --git a/src/Common/HyperLogLogBiasEstimator.h b/src/Common/HyperLogLogBiasEstimator.h index 9a334c88387..7943a623147 100644 --- a/src/Common/HyperLogLogBiasEstimator.h +++ b/src/Common/HyperLogLogBiasEstimator.h @@ -41,30 +41,28 @@ public: { return biases[estimates.size() - 1]; } - else if (*it == raw_estimate) + if (*it == raw_estimate) { size_t index = std::distance(estimates.begin(), it); return biases[index]; } - else if (it == estimates.begin()) + if (it == estimates.begin()) { return biases[0]; } - else - { - /// We get the error estimate by linear interpolation. - size_t index = std::distance(estimates.begin(), it); - double estimate1 = estimates[index - 1]; - double estimate2 = estimates[index]; + /// We get the error estimate by linear interpolation. + size_t index = std::distance(estimates.begin(), it); - double bias1 = biases[index - 1]; - double bias2 = biases[index]; - /// It is assumed that the estimate1 < estimate2 condition is always satisfied. - double slope = (bias2 - bias1) / (estimate2 - estimate1); + double estimate1 = estimates[index - 1]; + double estimate2 = estimates[index]; - return bias1 + slope * (raw_estimate - estimate1); - } + double bias1 = biases[index - 1]; + double bias2 = biases[index]; + /// It is assumed that the estimate1 < estimate2 condition is always satisfied. + double slope = (bias2 - bias1) / (estimate2 - estimate1); + + return bias1 + slope * (raw_estimate - estimate1); } private: diff --git a/src/Common/HyperLogLogCounter.h b/src/Common/HyperLogLogCounter.h index b3e509c782d..d20ba78af34 100644 --- a/src/Common/HyperLogLogCounter.h +++ b/src/Common/HyperLogLogCounter.h @@ -52,8 +52,7 @@ struct LogLUT { if (x <= M) return log_table[x]; - else - return log(static_cast(x)); + return log(static_cast(x)); } private: @@ -463,11 +462,11 @@ private: { if ((mode == HyperLogLogMode::Raw) || ((mode == HyperLogLogMode::BiasCorrected) && BiasEstimator::isTrivial())) return raw_estimate; - else if (mode == HyperLogLogMode::LinearCounting) + if (mode == HyperLogLogMode::LinearCounting) return applyLinearCorrection(raw_estimate); - else if ((mode == HyperLogLogMode::BiasCorrected) && !BiasEstimator::isTrivial()) + if ((mode == HyperLogLogMode::BiasCorrected) && !BiasEstimator::isTrivial()) return applyBiasCorrection(raw_estimate); - else if (mode == HyperLogLogMode::FullFeatured) + if (mode == HyperLogLogMode::FullFeatured) { static constexpr double pow2_32 = 4294967296.0; @@ -480,8 +479,7 @@ private: return fixed_estimate; } - else - throw Poco::Exception("Internal error", DB::ErrorCodes::LOGICAL_ERROR); + throw Poco::Exception("Internal error", DB::ErrorCodes::LOGICAL_ERROR); } double applyCorrection(double raw_estimate) const diff --git a/src/Common/IFactoryWithAliases.h b/src/Common/IFactoryWithAliases.h index 431e5c7b733..d3efbb6b761 100644 --- a/src/Common/IFactoryWithAliases.h +++ b/src/Common/IFactoryWithAliases.h @@ -29,10 +29,9 @@ protected: { if (aliases.contains(name)) return aliases.at(name); - else if (String name_lowercase = Poco::toLower(name); case_insensitive_aliases.contains(name_lowercase)) + if (String name_lowercase = Poco::toLower(name); case_insensitive_aliases.contains(name_lowercase)) return case_insensitive_aliases.at(name_lowercase); - else - return name; + return name; } std::unordered_map case_insensitive_name_mapping; @@ -102,7 +101,7 @@ public: { if (auto it = aliases.find(name); it != aliases.end()) return it->second; - else if (auto jt = case_insensitive_aliases.find(Poco::toLower(name)); jt != case_insensitive_aliases.end()) + if (auto jt = case_insensitive_aliases.find(Poco::toLower(name)); jt != case_insensitive_aliases.end()) return jt->second; throw Exception(ErrorCodes::LOGICAL_ERROR, "{}: name '{}' is not alias", getFactoryName(), name); diff --git a/src/Common/InterruptListener.h b/src/Common/InterruptListener.h index 1f0f021fb03..48ed97a2721 100644 --- a/src/Common/InterruptListener.h +++ b/src/Common/InterruptListener.h @@ -80,8 +80,7 @@ public: { if (errno == EAGAIN) return false; - else - throw ErrnoException(ErrorCodes::CANNOT_WAIT_FOR_SIGNAL, "Cannot poll signal (sigtimedwait)"); + throw ErrnoException(ErrorCodes::CANNOT_WAIT_FOR_SIGNAL, "Cannot poll signal (sigtimedwait)"); } return true; diff --git a/src/Common/LRUResourceCache.h b/src/Common/LRUResourceCache.h index 60b4053bff5..820eacf685a 100644 --- a/src/Common/LRUResourceCache.h +++ b/src/Common/LRUResourceCache.h @@ -230,14 +230,12 @@ private: queue.splice(queue.end(), queue, it->second.queue_iterator); return it->second.value; } - else if (it->second.reference_count > 0) + if (it->second.reference_count > 0) return nullptr; - else - { - // should not reach here - LOG_ERROR(getLogger("LRUResourceCache"), "element is in invalid status."); - abort(); - } + + // should not reach here + LOG_ERROR(getLogger("LRUResourceCache"), "element is in invalid status."); + abort(); } ++misses; auto & token = insert_tokens[key]; diff --git a/src/Common/Macros.cpp b/src/Common/Macros.cpp index 1d95037b38b..4b5300985e3 100644 --- a/src/Common/Macros.cpp +++ b/src/Common/Macros.cpp @@ -77,10 +77,9 @@ String Macros::expand(const String & s, res.append(s, pos, String::npos); break; } - else - { - res.append(s, pos, begin - pos); - } + + res.append(s, pos, begin - pos); + ++begin; size_t end = s.find('}', begin); diff --git a/src/Common/MemoryTracker.cpp b/src/Common/MemoryTracker.cpp index 7bf665ea7a0..3ed943f217d 100644 --- a/src/Common/MemoryTracker.cpp +++ b/src/Common/MemoryTracker.cpp @@ -289,11 +289,9 @@ AllocationTrace MemoryTracker::allocImpl(Int64 size, bool throw_if_memory_exceed size, formatReadableSizeWithBinarySuffix(current_hard_limit)); } - else - { - memory_limit_exceeded_ignored = true; - debugLogBigAllocationWithoutCheck(size); - } + + memory_limit_exceeded_ignored = true; + debugLogBigAllocationWithoutCheck(size); } if (unlikely( @@ -329,13 +327,11 @@ AllocationTrace MemoryTracker::allocImpl(Int64 size, bool throw_if_memory_exceed overcommit_result == OvercommitResult::NONE ? "" : " OvercommitTracker decision: ", toDescription(overcommit_result)); } - else - { - // If OvercommitTracker::needToStopQuery returned false, it guarantees that enough memory is freed. - // This memory is already counted in variable `amount` in the moment of `will_be` initialization. - // Now we just need to update value stored in `will_be`, because it should have changed. - will_be = amount.load(std::memory_order_relaxed); - } + + // If OvercommitTracker::needToStopQuery returned false, it guarantees that enough memory is freed. + // This memory is already counted in variable `amount` in the moment of `will_be` initialization. + // Now we just need to update value stored in `will_be`, because it should have changed. + will_be = amount.load(std::memory_order_relaxed); } else { diff --git a/src/Common/MemoryWorker.cpp b/src/Common/MemoryWorker.cpp index 11f3bff348c..7f84e6f9beb 100644 --- a/src/Common/MemoryWorker.cpp +++ b/src/Common/MemoryWorker.cpp @@ -170,11 +170,9 @@ std::shared_ptr ICgroupsReader::createCgroupsReader(ICgroupsRead { if (version == CgroupsVersion::V2) return std::make_shared(cgroup_path); - else - { - chassert(version == CgroupsVersion::V1); - return std::make_shared(cgroup_path); - } + + chassert(version == CgroupsVersion::V1); + return std::make_shared(cgroup_path); } #endif diff --git a/src/Common/NamedCollections/NamedCollectionsFactory.cpp b/src/Common/NamedCollections/NamedCollectionsFactory.cpp index b498684f33f..bfef74ad9fc 100644 --- a/src/Common/NamedCollections/NamedCollectionsFactory.cpp +++ b/src/Common/NamedCollections/NamedCollectionsFactory.cpp @@ -93,7 +93,7 @@ MutableNamedCollectionPtr NamedCollectionFactory::getMutable( "There is no named collection `{}`", collection_name); } - else if (!collection->isMutable()) + if (!collection->isMutable()) { throw Exception( ErrorCodes::NAMED_COLLECTION_IS_IMMUTABLE, diff --git a/src/Common/NamedCollections/NamedCollectionsMetadataStorage.cpp b/src/Common/NamedCollections/NamedCollectionsMetadataStorage.cpp index 0d6a6af4ef0..b8413bfadd7 100644 --- a/src/Common/NamedCollections/NamedCollectionsMetadataStorage.cpp +++ b/src/Common/NamedCollections/NamedCollectionsMetadataStorage.cpp @@ -540,13 +540,11 @@ void NamedCollectionsMetadataStorage::update(const ASTAlterNamedCollectionQuery "Cannot delete key `{}` because it does not exist in collection", delete_key); } - else - { - result_changes_map.erase(it); - auto it_override = result_overridability_map.find(delete_key); - if (it_override != result_overridability_map.end()) - result_overridability_map.erase(it_override); - } + + result_changes_map.erase(it); + auto it_override = result_overridability_map.find(delete_key); + if (it_override != result_overridability_map.end()) + result_overridability_map.erase(it_override); } create_query.changes.clear(); diff --git a/src/Common/NetlinkMetricsProvider.cpp b/src/Common/NetlinkMetricsProvider.cpp index f30186e715d..995b5c0642e 100644 --- a/src/Common/NetlinkMetricsProvider.cpp +++ b/src/Common/NetlinkMetricsProvider.cpp @@ -114,8 +114,7 @@ struct NetlinkMessage { if (bytes_sent < 0 && errno == EAGAIN) continue; - else - throw ErrnoException(ErrorCodes::NETLINK_ERROR, "Can't send a Netlink command"); + throw ErrnoException(ErrorCodes::NETLINK_ERROR, "Can't send a Netlink command"); } if (bytes_sent > request_size) diff --git a/src/Common/OptimizedRegularExpression.cpp b/src/Common/OptimizedRegularExpression.cpp index 2cdb3409487..94634f15ff0 100644 --- a/src/Common/OptimizedRegularExpression.cpp +++ b/src/Common/OptimizedRegularExpression.cpp @@ -571,27 +571,24 @@ bool OptimizedRegularExpression::match(const char * subject, size_t subject_size if (is_case_insensitive) return haystack_end != case_insensitive_substring_searcher->search(haystack, subject_size); - else - return haystack_end != case_sensitive_substring_searcher->search(haystack, subject_size); + return haystack_end != case_sensitive_substring_searcher->search(haystack, subject_size); } - else - { - if (!required_substring.empty()) - { - if (is_case_insensitive) - { - if (haystack_end == case_insensitive_substring_searcher->search(haystack, subject_size)) - return false; - } - else - { - if (haystack_end == case_sensitive_substring_searcher->search(haystack, subject_size)) - return false; - } - } - return re2->Match({subject, subject_size}, 0, subject_size, re2::RE2::UNANCHORED, nullptr, 0); + if (!required_substring.empty()) + { + if (is_case_insensitive) + { + if (haystack_end == case_insensitive_substring_searcher->search(haystack, subject_size)) + return false; + } + else + { + if (haystack_end == case_sensitive_substring_searcher->search(haystack, subject_size)) + return false; + } } + + return re2->Match({subject, subject_size}, 0, subject_size, re2::RE2::UNANCHORED, nullptr, 0); } @@ -613,38 +610,32 @@ bool OptimizedRegularExpression::match(const char * subject, size_t subject_size if (haystack_end == pos) return false; - else - { - match.offset = pos - haystack; - match.length = required_substring.size(); - return true; - } + + match.offset = pos - haystack; + match.length = required_substring.size(); + return true; } - else + + if (!required_substring.empty()) { - if (!required_substring.empty()) - { - const UInt8 * pos; - if (is_case_insensitive) - pos = case_insensitive_substring_searcher->search(haystack, subject_size); - else - pos = case_sensitive_substring_searcher->search(haystack, subject_size); - - if (haystack_end == pos) - return false; - } - - std::string_view piece; - - if (!re2::RE2::PartialMatch({subject, subject_size}, *re2, &piece)) - return false; + const UInt8 * pos; + if (is_case_insensitive) + pos = case_insensitive_substring_searcher->search(haystack, subject_size); else - { - match.offset = piece.data() - subject; - match.length = piece.length(); - return true; - } + pos = case_sensitive_substring_searcher->search(haystack, subject_size); + + if (haystack_end == pos) + return false; } + + std::string_view piece; + + if (!re2::RE2::PartialMatch({subject, subject_size}, *re2, &piece)) + return false; + + match.offset = piece.data() - subject; + match.length = piece.length(); + return true; } @@ -676,58 +667,46 @@ unsigned OptimizedRegularExpression::match(const char * subject, size_t subject_ if (haystack_end == pos) return 0; - else - { - Match match; - match.offset = pos - haystack; - match.length = required_substring.size(); - matches.push_back(match); - return 1; - } + + Match match; + match.offset = pos - haystack; + match.length = required_substring.size(); + matches.push_back(match); + return 1; } - else + + if (!required_substring.empty()) { - if (!required_substring.empty()) - { - const UInt8 * pos; - if (is_case_insensitive) - pos = case_insensitive_substring_searcher->search(haystack, subject_size); - else - pos = case_sensitive_substring_searcher->search(haystack, subject_size); + const UInt8 * pos; + if (is_case_insensitive) + pos = case_insensitive_substring_searcher->search(haystack, subject_size); + else + pos = case_sensitive_substring_searcher->search(haystack, subject_size); - if (haystack_end == pos) - return 0; - } - - DB::PODArrayWithStackMemory pieces(limit); - - if (!re2->Match( - {subject, subject_size}, - 0, - subject_size, - re2::RE2::UNANCHORED, - pieces.data(), - static_cast(pieces.size()))) - { + if (haystack_end == pos) return 0; + } + + DB::PODArrayWithStackMemory pieces(limit); + + if (!re2->Match({subject, subject_size}, 0, subject_size, re2::RE2::UNANCHORED, pieces.data(), static_cast(pieces.size()))) + { + return 0; + } + + matches.resize(limit); + for (size_t i = 0; i < limit; ++i) + { + if (pieces[i].empty()) + { + matches[i].offset = std::string::npos; + matches[i].length = 0; } else { - matches.resize(limit); - for (size_t i = 0; i < limit; ++i) - { - if (pieces[i].empty()) - { - matches[i].offset = std::string::npos; - matches[i].length = 0; - } - else - { - matches[i].offset = pieces[i].data() - subject; - matches[i].length = pieces[i].length(); - } - } - return limit; + matches[i].offset = pieces[i].data() - subject; + matches[i].length = pieces[i].length(); } } + return limit; } diff --git a/src/Common/OvercommitTracker.cpp b/src/Common/OvercommitTracker.cpp index 2f067b7c193..2a453596dab 100644 --- a/src/Common/OvercommitTracker.cpp +++ b/src/Common/OvercommitTracker.cpp @@ -105,8 +105,7 @@ OvercommitResult OvercommitTracker::needToStopQuery(MemoryTracker * tracker, Int return OvercommitResult::TIMEOUTED; if (still_need) return OvercommitResult::NOT_ENOUGH_FREED; - else - return OvercommitResult::MEMORY_FREED; + return OvercommitResult::MEMORY_FREED; } void OvercommitTracker::tryContinueQueryExecutionAfterFree(Int64 amount) diff --git a/src/Common/PODArray.h b/src/Common/PODArray.h index 92ef0597c7e..48f2ffee8ce 100644 --- a/src/Common/PODArray.h +++ b/src/Common/PODArray.h @@ -631,12 +631,12 @@ public: { return; } - else if (!this->isInitialized() && rhs.isInitialized()) + if (!this->isInitialized() && rhs.isInitialized()) { do_move(rhs, *this); return; } - else if (this->isInitialized() && !rhs.isInitialized()) + if (this->isInitialized() && !rhs.isInitialized()) { do_move(*this, rhs); return; diff --git a/src/Common/PageCache.cpp b/src/Common/PageCache.cpp index d719a387e14..a8937c99c5a 100644 --- a/src/Common/PageCache.cpp +++ b/src/Common/PageCache.cpp @@ -112,8 +112,7 @@ bool AtomicBitSet::set(size_t i, bool val) const { if (val) return set(i); - else - return unset(i); + return unset(i); } bool AtomicBitSet::unset(size_t i) const diff --git a/src/Common/PoolBase.h b/src/Common/PoolBase.h index fb0c75e7c95..a3ee9b8e6e1 100644 --- a/src/Common/PoolBase.h +++ b/src/Common/PoolBase.h @@ -134,13 +134,11 @@ public: { return Entry(*item); } - else - { - expireObject(item->object); - item->object = allocObject(); - item->is_expired = false; - return Entry(*item); - } + + expireObject(item->object); + item->object = allocObject(); + item->is_expired = false; + return Entry(*item); } } if (items.size() < max_items) diff --git a/src/Common/PoolWithFailoverBase.h b/src/Common/PoolWithFailoverBase.h index 989ffd888f8..c4c2ef74dbb 100644 --- a/src/Common/PoolWithFailoverBase.h +++ b/src/Common/PoolWithFailoverBase.h @@ -376,9 +376,8 @@ struct PoolWithFailoverBase::PoolState if (use_slowdown_count) return std::forward_as_tuple(lhs.error_count, lhs.slowdown_count, lhs.config_priority, lhs.priority, lhs.random) < std::forward_as_tuple(rhs.error_count, rhs.slowdown_count, rhs.config_priority, rhs.priority, rhs.random); - else - return std::forward_as_tuple(lhs.error_count, lhs.config_priority, lhs.priority, lhs.random) - < std::forward_as_tuple(rhs.error_count, rhs.config_priority, rhs.priority, rhs.random); + return std::forward_as_tuple(lhs.error_count, lhs.config_priority, lhs.priority, lhs.random) + < std::forward_as_tuple(rhs.error_count, rhs.config_priority, rhs.priority, rhs.random); } private: diff --git a/src/Common/ProxyConfiguration.h b/src/Common/ProxyConfiguration.h index a9921f1474d..f4a294ba2a4 100644 --- a/src/Common/ProxyConfiguration.h +++ b/src/Common/ProxyConfiguration.h @@ -25,7 +25,7 @@ struct ProxyConfiguration { return Protocol::HTTP; } - else if (str == "https") + if (str == "https") { return Protocol::HTTPS; } diff --git a/src/Common/ProxyConfigurationResolverProvider.cpp b/src/Common/ProxyConfigurationResolverProvider.cpp index a46837bfdb9..a16c8b79627 100644 --- a/src/Common/ProxyConfigurationResolverProvider.cpp +++ b/src/Common/ProxyConfigurationResolverProvider.cpp @@ -170,13 +170,13 @@ std::shared_ptr ProxyConfigurationResolverProvider:: { return nullptr; } - auto prefix = *prefix_opt; + const auto & prefix = *prefix_opt; if (hasRemoteResolver(prefix, configuration)) { return getRemoteResolver(request_protocol, prefix, configuration); } - else if (hasListResolver(prefix, configuration)) + if (hasListResolver(prefix, configuration)) { return getListResolver(request_protocol, prefix, configuration); } diff --git a/src/Common/QueryFuzzer.cpp b/src/Common/QueryFuzzer.cpp index 2122f7355f4..ae0b39ea14e 100644 --- a/src/Common/QueryFuzzer.cpp +++ b/src/Common/QueryFuzzer.cpp @@ -760,35 +760,35 @@ ASTExplainQuery::ExplainKind QueryFuzzer::fuzzExplainKind(ASTExplainQuery::Expla { return kind; } - else if (fuzz_rand() % 11 == 0) + if (fuzz_rand() % 11 == 0) { return ASTExplainQuery::ExplainKind::ParsedAST; } - else if (fuzz_rand() % 11 == 0) + if (fuzz_rand() % 11 == 0) { return ASTExplainQuery::ExplainKind::AnalyzedSyntax; } - else if (fuzz_rand() % 11 == 0) + if (fuzz_rand() % 11 == 0) { return ASTExplainQuery::ExplainKind::QueryTree; } - else if (fuzz_rand() % 11 == 0) + if (fuzz_rand() % 11 == 0) { return ASTExplainQuery::ExplainKind::QueryPlan; } - else if (fuzz_rand() % 11 == 0) + if (fuzz_rand() % 11 == 0) { return ASTExplainQuery::ExplainKind::QueryPipeline; } - else if (fuzz_rand() % 11 == 0) + if (fuzz_rand() % 11 == 0) { return ASTExplainQuery::ExplainKind::QueryEstimates; } - else if (fuzz_rand() % 11 == 0) + if (fuzz_rand() % 11 == 0) { return ASTExplainQuery::ExplainKind::TableOverride; } - else if (fuzz_rand() % 11 == 0) + if (fuzz_rand() % 11 == 0) { return ASTExplainQuery::ExplainKind::CurrentTransaction; } @@ -1287,7 +1287,7 @@ void QueryFuzzer::addTableLike(ASTPtr ast) if (table_like_map.size() > AST_FUZZER_PART_TYPE_CAP) { const auto iter = std::next(table_like.begin(), fuzz_rand() % table_like.size()); - const auto ast_del = *iter; + const auto & ast_del = *iter; table_like.erase(iter); table_like_map.erase(ast_del.first); } @@ -1308,7 +1308,7 @@ void QueryFuzzer::addColumnLike(ASTPtr ast) if (column_like_map.size() > AST_FUZZER_PART_TYPE_CAP) { const auto iter = std::next(column_like.begin(), fuzz_rand() % column_like.size()); - const auto ast_del = *iter; + const auto & ast_del = *iter; column_like.erase(iter); column_like_map.erase(ast_del.first); } diff --git a/src/Common/RadixSort.h b/src/Common/RadixSort.h index 238321ec76e..9fd17084e47 100644 --- a/src/Common/RadixSort.h +++ b/src/Common/RadixSort.h @@ -599,16 +599,12 @@ public: if (destination) return executeLSDWithTrySortInternal(arr, size, reverse, GreaterComparator(), destination); - else - return executeLSDWithTrySortInternal(arr, size, reverse, GreaterComparator(), destination); - } - else - { - if (destination) - return executeLSDWithTrySortInternal(arr, size, reverse, LessComparator(), destination); - else - return executeLSDWithTrySortInternal(arr, size, reverse, LessComparator(), destination); + return executeLSDWithTrySortInternal(arr, size, reverse, GreaterComparator(), destination); } + + if (destination) + return executeLSDWithTrySortInternal(arr, size, reverse, LessComparator(), destination); + return executeLSDWithTrySortInternal(arr, size, reverse, LessComparator(), destination); } /* Most significant digit radix sort diff --git a/src/Common/Scheduler/ISchedulerNode.h b/src/Common/Scheduler/ISchedulerNode.h index c051829e336..0705c4f0a35 100644 --- a/src/Common/Scheduler/ISchedulerNode.h +++ b/src/Common/Scheduler/ISchedulerNode.h @@ -338,15 +338,13 @@ public: } if (postponed.empty()) return false; - else + + if (postponed.front().key <= now()) { - if (postponed.front().key <= now()) - { - processPostponed(std::move(lock)); - return true; - } - return false; + processPostponed(std::move(lock)); + return true; } + return false; } /// Wait for single event (if not available) and process it @@ -360,7 +358,7 @@ public: processQueue(std::move(lock)); return; } - else if (postponed.empty()) + if (postponed.empty()) { wait(lock); } @@ -371,20 +369,18 @@ public: processPostponed(std::move(lock)); return; } - else - { - waitUntil(lock, postponed.front().key); - } + + waitUntil(lock, postponed.front().key); } } } TimePoint now() { - if (auto result = manual_time.load(); likely(result == TimePoint())) + auto result = manual_time.load(); + if (likely(result == TimePoint())) return std::chrono::system_clock::now(); - else - return result; + return result; } /// For testing only diff --git a/src/Common/Scheduler/Nodes/ClassifiersConfig.cpp b/src/Common/Scheduler/Nodes/ClassifiersConfig.cpp index 192f97645a0..3be61801149 100644 --- a/src/Common/Scheduler/Nodes/ClassifiersConfig.cpp +++ b/src/Common/Scheduler/Nodes/ClassifiersConfig.cpp @@ -33,8 +33,7 @@ const ClassifierDescription & ClassifiersConfig::get(const String & classifier_n { if (auto it = classifiers.find(classifier_name); it != classifiers.end()) return it->second; - else - throw Exception(ErrorCodes::RESOURCE_NOT_FOUND, "Unknown workload classifier '{}' to access resources", classifier_name); + throw Exception(ErrorCodes::RESOURCE_NOT_FOUND, "Unknown workload classifier '{}' to access resources", classifier_name); } } diff --git a/src/Common/Scheduler/Nodes/DynamicResourceManager.cpp b/src/Common/Scheduler/Nodes/DynamicResourceManager.cpp index 6b9f6318903..5bf884fc3df 100644 --- a/src/Common/Scheduler/Nodes/DynamicResourceManager.cpp +++ b/src/Common/Scheduler/Nodes/DynamicResourceManager.cpp @@ -166,8 +166,7 @@ ResourceLink DynamicResourceManager::Classifier::get(const String & resource_nam { if (auto iter = resources.find(resource_name); iter != resources.end()) return iter->second; - else - throw Exception(ErrorCodes::RESOURCE_ACCESS_DENIED, "Access denied to resource '{}'", resource_name); + throw Exception(ErrorCodes::RESOURCE_ACCESS_DENIED, "Access denied to resource '{}'", resource_name); } DynamicResourceManager::DynamicResourceManager() diff --git a/src/Common/Scheduler/Nodes/FairPolicy.h b/src/Common/Scheduler/Nodes/FairPolicy.h index 1a4c7b94b28..246642ff2fd 100644 --- a/src/Common/Scheduler/Nodes/FairPolicy.h +++ b/src/Common/Scheduler/Nodes/FairPolicy.h @@ -128,8 +128,7 @@ public: { if (auto iter = children.find(child_name); iter != children.end()) return iter->second.get(); - else - return nullptr; + return nullptr; } std::pair dequeueRequest() override diff --git a/src/Common/Scheduler/Nodes/PriorityPolicy.h b/src/Common/Scheduler/Nodes/PriorityPolicy.h index 88fa8c240ca..b170ab0dbee 100644 --- a/src/Common/Scheduler/Nodes/PriorityPolicy.h +++ b/src/Common/Scheduler/Nodes/PriorityPolicy.h @@ -96,8 +96,7 @@ public: { if (auto iter = children.find(child_name); iter != children.end()) return iter->second.get(); - else - return nullptr; + return nullptr; } std::pair dequeueRequest() override diff --git a/src/Common/Scheduler/Nodes/SemaphoreConstraint.h b/src/Common/Scheduler/Nodes/SemaphoreConstraint.h index 92c6af9db18..fe1b03b74bd 100644 --- a/src/Common/Scheduler/Nodes/SemaphoreConstraint.h +++ b/src/Common/Scheduler/Nodes/SemaphoreConstraint.h @@ -58,8 +58,7 @@ public: { if (child->basename == child_name) return child.get(); - else - return nullptr; + return nullptr; } std::pair dequeueRequest() override diff --git a/src/Common/Scheduler/Nodes/ThrottlerConstraint.h b/src/Common/Scheduler/Nodes/ThrottlerConstraint.h index 56866336f50..b279cbe972b 100644 --- a/src/Common/Scheduler/Nodes/ThrottlerConstraint.h +++ b/src/Common/Scheduler/Nodes/ThrottlerConstraint.h @@ -68,8 +68,7 @@ public: { if (child->basename == child_name) return child.get(); - else - return nullptr; + return nullptr; } std::pair dequeueRequest() override diff --git a/src/Common/Scheduler/SchedulerRoot.h b/src/Common/Scheduler/SchedulerRoot.h index 4ba6bc65e1c..6a3c3962eb1 100644 --- a/src/Common/Scheduler/SchedulerRoot.h +++ b/src/Common/Scheduler/SchedulerRoot.h @@ -221,8 +221,8 @@ private: busy_periods++; return; } - else // Just move current to next to avoid invalidation - current = current->next; + // Just move current to next to avoid invalidation + current = current->next; } value->prev->next = value->next; value->next->prev = value->prev; diff --git a/src/Common/SignalHandlers.cpp b/src/Common/SignalHandlers.cpp index 554a56f22e8..7ab001d6d34 100644 --- a/src/Common/SignalHandlers.cpp +++ b/src/Common/SignalHandlers.cpp @@ -275,7 +275,7 @@ void SignalListener::run() LOG_INFO(log, "Stop SignalListener thread"); break; } - else if (sig == SIGHUP) + if (sig == SIGHUP) { LOG_DEBUG(log, "Received signal to close logs."); BaseDaemon::instance().closeLogs(BaseDaemon::instance().logger()); @@ -291,9 +291,7 @@ void SignalListener::run() onTerminate(message, thread_num); } - else if (sig == SIGINT || - sig == SIGQUIT || - sig == SIGTERM) + else if (sig == SIGINT || sig == SIGQUIT || sig == SIGTERM) { if (daemon) daemon->handleSignal(sig); @@ -323,7 +321,8 @@ void SignalListener::run() /// Example: segfault while symbolizing stack trace. try { - std::thread([=, this] { onFault(sig, info, context, stack_trace, thread_frame_pointers, thread_num, thread_ptr); }).detach(); + std::thread([=, this] { onFault(sig, info, context, stack_trace, thread_frame_pointers, thread_num, thread_ptr); }) + .detach(); } catch (...) { diff --git a/src/Common/StatusFile.cpp b/src/Common/StatusFile.cpp index 3e7c5d4788b..f4149a055c0 100644 --- a/src/Common/StatusFile.cpp +++ b/src/Common/StatusFile.cpp @@ -73,8 +73,7 @@ StatusFile::StatusFile(std::string path_, FillFunction fill_) { if (errno == EWOULDBLOCK) throw Exception(ErrorCodes::CANNOT_OPEN_FILE, "Cannot lock file {}. Another server instance in same directory is already running.", path); - else - ErrnoException::throwFromPath(ErrorCodes::CANNOT_OPEN_FILE, path, "Cannot lock file {}", path); + ErrnoException::throwFromPath(ErrorCodes::CANNOT_OPEN_FILE, path, "Cannot lock file {}", path); } if (0 != ftruncate(fd, 0)) diff --git a/src/Common/StudentTTest.cpp b/src/Common/StudentTTest.cpp index 6a3c7d7c014..87f041d6bcd 100644 --- a/src/Common/StudentTTest.cpp +++ b/src/Common/StudentTTest.cpp @@ -162,9 +162,7 @@ std::pair StudentTTest::compareAndReport(size_t confidence_le out << "mean difference is " << mean_difference << ", but confidence interval is " << mean_confidence_interval; return {false, out.str()}; } - else - { - out << "No difference proven at " << confidence_level[confidence_level_index] << "% confidence"; - return {true, out.str()}; - } + + out << "No difference proven at " << confidence_level[confidence_level_index] << "% confidence"; + return {true, out.str()}; } diff --git a/src/Common/SymbolIndex.cpp b/src/Common/SymbolIndex.cpp index f8ced95653b..f16c623cefa 100644 --- a/src/Common/SymbolIndex.cpp +++ b/src/Common/SymbolIndex.cpp @@ -460,13 +460,11 @@ const T * find(const void * address, const std::vector & vec) if (it == vec.begin()) return nullptr; - else - --it; /// Last range that has left boundary less or equals than address. + --it; /// Last range that has left boundary less or equals than address. if (address >= it->address_begin && address < it->address_end) return &*it; - else - return nullptr; + return nullptr; } } diff --git a/src/Common/SystemLogBase.cpp b/src/Common/SystemLogBase.cpp index 45f4eb1c5a6..1bd79999cd7 100644 --- a/src/Common/SystemLogBase.cpp +++ b/src/Common/SystemLogBase.cpp @@ -157,8 +157,7 @@ void SystemLogQueue::waitFlush(SystemLogQueue::Index exp { if (should_prepare_tables_anyway) return (flushed_index >= expected_flushed_index && prepared_tables >= requested_prepare_tables) || is_shutdown; - else - return (flushed_index >= expected_flushed_index) || is_shutdown; + return (flushed_index >= expected_flushed_index) || is_shutdown; }); if (!result) diff --git a/src/Common/ThreadFuzzer.cpp b/src/Common/ThreadFuzzer.cpp index 719ac9593ff..afeef24a89f 100644 --- a/src/Common/ThreadFuzzer.cpp +++ b/src/Common/ThreadFuzzer.cpp @@ -1,4 +1,4 @@ -// NOLINTBEGIN(readability-inconsistent-declaration-parameter-name) +// NOLINTBEGIN(readability-inconsistent-declaration-parameter-name,readability-else-after-return) #include #include @@ -450,4 +450,4 @@ FOR_EACH_WRAPPED_FUNCTION(MAKE_WRAPPER_USING_INTERNAL_SYMBOLS) #endif } -// NOLINTEND(readability-inconsistent-declaration-parameter-name) +// NOLINTEND(readability-inconsistent-declaration-parameter-name,readability-else-after-return) diff --git a/src/Common/ThreadProfileEvents.cpp b/src/Common/ThreadProfileEvents.cpp index 23b41f23bde..25d16935b13 100644 --- a/src/Common/ThreadProfileEvents.cpp +++ b/src/Common/ThreadProfileEvents.cpp @@ -100,7 +100,7 @@ TasksStatsCounters::MetricsProvider TasksStatsCounters::findBestAvailableProvide { return MetricsProvider::Netlink; } - else if (ProcfsMetricsProvider::isAvailable()) + if (ProcfsMetricsProvider::isAvailable()) { return MetricsProvider::Procfs; } diff --git a/src/Common/UTF8Helpers.cpp b/src/Common/UTF8Helpers.cpp index dd24cb20933..22f2753a8a9 100644 --- a/src/Common/UTF8Helpers.cpp +++ b/src/Common/UTF8Helpers.cpp @@ -133,11 +133,9 @@ size_t computeWidthImpl(const UInt8 * data, size_t size, size_t prefix, size_t l i += num_regular_chars; break; } - else - { - i += 16; - width += 16; - } + + i += 16; + width += 16; } #endif diff --git a/src/Common/VersionNumber.cpp b/src/Common/VersionNumber.cpp index cb02f6f8db2..d1dca0213af 100644 --- a/src/Common/VersionNumber.cpp +++ b/src/Common/VersionNumber.cpp @@ -40,7 +40,7 @@ int VersionNumber::compare(const VersionNumber & rhs) const { return components[min] >= 0 ? 1 : -1; } - else if (rhs.components.size() > min) + if (rhs.components.size() > min) { return -rhs.components[min] > 0 ? 1 : -1; } diff --git a/src/Common/Volnitsky.h b/src/Common/Volnitsky.h index 3f8e1927493..f9d0fc1e1e2 100644 --- a/src/Common/Volnitsky.h +++ b/src/Common/Volnitsky.h @@ -134,6 +134,7 @@ namespace VolnitskyTraits n = toNGram(pos); + /// NOLINTBEGIN(readability-else-after-return) if (isascii(chars.c0) && isascii(chars.c1)) { return putNGramASCIICaseInsensitive(pos, offset, putNGramBase); @@ -346,6 +347,7 @@ namespace VolnitskyTraits } } return true; + /// NOLINTEND(readability-else-after-return) } template diff --git a/src/Common/ZooKeeper/ZooKeeper.cpp b/src/Common/ZooKeeper/ZooKeeper.cpp index fb6d0a27d5c..1c6a99e1f32 100644 --- a/src/Common/ZooKeeper/ZooKeeper.cpp +++ b/src/Common/ZooKeeper/ZooKeeper.cpp @@ -301,18 +301,16 @@ Coordination::Error ZooKeeper::getChildrenImpl(const std::string & path, Strings impl->finalize(fmt::format("Operation timeout on {} {}", Coordination::OpNum::List, path)); return Coordination::Error::ZOPERATIONTIMEOUT; } - else + + auto response = future_result.get(); + Coordination::Error code = response.error; + if (code == Coordination::Error::ZOK) { - auto response = future_result.get(); - Coordination::Error code = response.error; - if (code == Coordination::Error::ZOK) - { - res = response.names; - if (stat) - *stat = response.stat; - } - return code; + res = response.names; + if (stat) + *stat = response.stat; } + return code; } Strings ZooKeeper::getChildren(const std::string & path, Coordination::Stat * stat, const EventPtr & watch, Coordination::ListRequestType list_request_type) @@ -384,14 +382,12 @@ Coordination::Error ZooKeeper::createImpl(const std::string & path, const std::s impl->finalize(fmt::format("Operation timeout on {} {}", Coordination::OpNum::Create, path)); return Coordination::Error::ZOPERATIONTIMEOUT; } - else - { - auto response = future_result.get(); - Coordination::Error code = response.error; - if (code == Coordination::Error::ZOK) - path_created = response.path_created; - return code; - } + + auto response = future_result.get(); + Coordination::Error code = response.error; + if (code == Coordination::Error::ZOK) + path_created = response.path_created; + return code; } std::string ZooKeeper::create(const std::string & path, const std::string & data, int32_t mode) @@ -430,10 +426,9 @@ void ZooKeeper::createIfNotExists(const std::string & path, const std::string & if (code == Coordination::Error::ZOK || code == Coordination::Error::ZNODEEXISTS) return; - else if (code == Coordination::Error::ZNOTREADONLY && exists(path)) + if (code == Coordination::Error::ZNOTREADONLY && exists(path)) return; - else - throw KeeperException::fromPath(code, path); + throw KeeperException::fromPath(code, path); } void ZooKeeper::createAncestors(const std::string & path) @@ -534,11 +529,9 @@ Coordination::Error ZooKeeper::removeImpl(const std::string & path, int32_t vers impl->finalize(fmt::format("Operation timeout on {} {}", Coordination::OpNum::Remove, path)); return Coordination::Error::ZOPERATIONTIMEOUT; } - else - { - auto response = future_result.get(); - return response.error; - } + + auto response = future_result.get(); + return response.error; } void ZooKeeper::remove(const std::string & path, int32_t version) @@ -566,15 +559,13 @@ Coordination::Error ZooKeeper::existsImpl(const std::string & path, Coordination impl->finalize(fmt::format("Operation timeout on {} {}", Coordination::OpNum::Exists, path)); return Coordination::Error::ZOPERATIONTIMEOUT; } - else - { - auto response = future_result.get(); - Coordination::Error code = response.error; - if (code == Coordination::Error::ZOK && stat) - *stat = response.stat; - return code; - } + auto response = future_result.get(); + Coordination::Error code = response.error; + if (code == Coordination::Error::ZOK && stat) + *stat = response.stat; + + return code; } bool ZooKeeper::exists(const std::string & path, Coordination::Stat * stat, const EventPtr & watch) @@ -612,18 +603,16 @@ Coordination::Error ZooKeeper::getImpl( impl->finalize(fmt::format("Operation timeout on {} {}", Coordination::OpNum::Get, path)); return Coordination::Error::ZOPERATIONTIMEOUT; } - else + + auto response = future_result.get(); + Coordination::Error code = response.error; + if (code == Coordination::Error::ZOK) { - auto response = future_result.get(); - Coordination::Error code = response.error; - if (code == Coordination::Error::ZOK) - { - res = response.data; - if (stat) - *stat = response.stat; - } - return code; + res = response.data; + if (stat) + *stat = response.stat; } + return code; } Coordination::Error ZooKeeper::getImpl(const std::string & path, std::string & res, Coordination::Stat * stat, Coordination::WatchCallback watch_callback) @@ -637,8 +626,7 @@ std::string ZooKeeper::get(const std::string & path, Coordination::Stat * stat, std::string res; if (tryGet(path, res, stat, watch, &code)) return res; - else - throw KeeperException(code, "Can't get data for node '{}': node doesn't exist", path); + throw KeeperException(code, "Can't get data for node '{}': node doesn't exist", path); } std::string ZooKeeper::getWatch(const std::string & path, Coordination::Stat * stat, Coordination::WatchCallback watch_callback) @@ -647,8 +635,7 @@ std::string ZooKeeper::getWatch(const std::string & path, Coordination::Stat * s std::string res; if (tryGetWatch(path, res, stat, watch_callback, &code)) return res; - else - throw KeeperException(code, "Can't get data for node '{}': node doesn't exist", path); + throw KeeperException(code, "Can't get data for node '{}': node doesn't exist", path); } @@ -658,8 +645,7 @@ std::string ZooKeeper::getWatch(const std::string & path, Coordination::Stat * s std::string res; if (tryGetWatch(path, res, stat, watch_callback, &code)) return res; - else - throw KeeperException(code, "Can't get data for node '{}': node doesn't exist", path); + throw KeeperException(code, "Can't get data for node '{}': node doesn't exist", path); } bool ZooKeeper::tryGet( @@ -720,15 +706,13 @@ Coordination::Error ZooKeeper::setImpl(const std::string & path, const std::stri impl->finalize(fmt::format("Operation timeout on {} {}", Coordination::OpNum::Set, path)); return Coordination::Error::ZOPERATIONTIMEOUT; } - else - { - auto response = future_result.get(); - Coordination::Error code = response.error; - if (code == Coordination::Error::ZOK && stat) - *stat = response.stat; - return code; - } + auto response = future_result.get(); + Coordination::Error code = response.error; + if (code == Coordination::Error::ZOK && stat) + *stat = response.stat; + + return code; } void ZooKeeper::set(const std::string & path, const std::string & data, int32_t version, Coordination::Stat * stat) @@ -784,30 +768,30 @@ ZooKeeper::multiImpl(const Coordination::Requests & requests, Coordination::Resp impl->finalize(fmt::format("Operation timeout on {} {}", Coordination::OpNum::Multi, requests[0]->getPath())); return {Coordination::Error::ZOPERATIONTIMEOUT, ""}; } - else + + auto response = future_result.get(); + Coordination::Error code = response.error; + responses = response.responses; + + std::string reason; + + if (check_session_valid) { - auto response = future_result.get(); - Coordination::Error code = response.error; - responses = response.responses; - - std::string reason; - - if (check_session_valid) + if (code != Coordination::Error::ZOK && !Coordination::isHardwareError(code) + && getFailedOpIndex(code, responses) == requests.size()) { - if (code != Coordination::Error::ZOK && !Coordination::isHardwareError(code) && getFailedOpIndex(code, responses) == requests.size()) - { - reason = fmt::format("Session was killed: {}", requests_with_check_session.back()->getPath()); - impl->finalize(reason); - code = Coordination::Error::ZSESSIONMOVED; - } - responses.pop_back(); - /// For some reason, for hardware errors we set ZOK codes for all responses. - /// In other cases, if the multi-request status is not ZOK, then the last response status must indicate an error too - chassert(code == Coordination::Error::ZOK || Coordination::isHardwareError(code) || responses.back()->error != Coordination::Error::ZOK); + reason = fmt::format("Session was killed: {}", requests_with_check_session.back()->getPath()); + impl->finalize(reason); + code = Coordination::Error::ZSESSIONMOVED; } - - return {code, std::move(reason)}; + responses.pop_back(); + /// For some reason, for hardware errors we set ZOK codes for all responses. + /// In other cases, if the multi-request status is not ZOK, then the last response status must indicate an error too + chassert( + code == Coordination::Error::ZOK || Coordination::isHardwareError(code) || responses.back()->error != Coordination::Error::ZOK); } + + return {code, std::move(reason)}; } Coordination::Responses ZooKeeper::multi(const Coordination::Requests & requests, bool check_session_valid) @@ -845,13 +829,11 @@ Coordination::Error ZooKeeper::syncImpl(const std::string & path, std::string & impl->finalize(fmt::format("Operation timeout on {} {}", Coordination::OpNum::Sync, path)); return Coordination::Error::ZOPERATIONTIMEOUT; } - else - { - auto response = future_result.get(); - Coordination::Error code = response.error; - returned_path = std::move(response.path); - return code; - } + + auto response = future_result.get(); + Coordination::Error code = response.error; + returned_path = std::move(response.path); + return code; } std::string ZooKeeper::sync(const std::string & path) { @@ -1014,11 +996,9 @@ Coordination::Error ZooKeeper::tryRemoveRecursive(const std::string & path, uint impl->finalize(fmt::format("Operation timeout on {} {}", Coordination::OpNum::RemoveRecursive, path)); return Coordination::Error::ZOPERATIONTIMEOUT; } - else - { - auto response = future.get(); - return response.error; - } + + auto response = future.get(); + return response.error; } namespace @@ -1624,8 +1604,7 @@ void KeeperMultiException::check( if (Coordination::isUserError(exception_code)) throw KeeperMultiException(exception_code, requests, responses); - else - throw KeeperException(exception_code); + throw KeeperException(exception_code); } diff --git a/src/Common/ZooKeeper/ZooKeeperImpl.cpp b/src/Common/ZooKeeper/ZooKeeperImpl.cpp index 510ebd4f82d..d7d0f400d2e 100644 --- a/src/Common/ZooKeeper/ZooKeeperImpl.cpp +++ b/src/Common/ZooKeeper/ZooKeeperImpl.cpp @@ -473,8 +473,7 @@ void ZooKeeper::connect( if (dns_error) throw zkutil::KeeperException::fromMessage( Coordination::Error::ZCONNECTIONLOSS, "Cannot resolve any of provided ZooKeeper hosts due to DNS error"); - else - throw zkutil::KeeperException::fromMessage(Coordination::Error::ZCONNECTIONLOSS, "Cannot use any of provided ZooKeeper nodes"); + throw zkutil::KeeperException::fromMessage(Coordination::Error::ZCONNECTIONLOSS, "Cannot use any of provided ZooKeeper nodes"); } WriteBufferFromOwnString fail_reasons; @@ -577,10 +576,8 @@ void ZooKeeper::connect( message << fail_reasons.str() << "\n"; throw Exception(Error::ZCONNECTIONLOSS, "All connection tries failed while connecting to ZooKeeper. nodes: {}", message.str()); } - else - { - LOG_INFO(log, "Connected to ZooKeeper at {} with session_id {}{}", socket.peerAddress().toString(), session_id, fail_reasons.str()); - } + + LOG_INFO(log, "Connected to ZooKeeper at {} with session_id {}{}", socket.peerAddress().toString(), session_id, fail_reasons.str()); } @@ -1286,7 +1283,7 @@ std::optional ZooKeeper::tryGetSystemZnode(const std::string & path, con LOG_TRACE(log, "Failed to get {}", description); return std::nullopt; } - else if (response.error != Coordination::Error::ZOK) + if (response.error != Coordination::Error::ZOK) { throw Exception(response.error, "Failed to get {}", description); } @@ -1593,8 +1590,7 @@ std::optional ZooKeeper::getConnectedNodeIdx() const int8_t res = original_index.load(); if (res == -1) return std::nullopt; - else - return res; + return res; } String ZooKeeper::getConnectedHostPort() const @@ -1602,8 +1598,7 @@ String ZooKeeper::getConnectedHostPort() const auto idx = getConnectedNodeIdx(); if (idx) return args.hosts[*idx]; - else - return ""; + return ""; } int64_t ZooKeeper::getConnectionXid() const diff --git a/src/Common/assertProcessUserMatchesDataOwner.cpp b/src/Common/assertProcessUserMatchesDataOwner.cpp index a2f87825257..ec7195cd334 100644 --- a/src/Common/assertProcessUserMatchesDataOwner.cpp +++ b/src/Common/assertProcessUserMatchesDataOwner.cpp @@ -57,10 +57,8 @@ void assertProcessUserMatchesDataOwner(const std::string & path, std::functionsecond, true); } - else - { - auto & iterator_in_list_to_update = it->second; - list.splice(list.end(), list, iterator_in_list_to_update); - iterator_in_list_to_update = --list.end(); + auto & iterator_in_list_to_update = it->second; - return std::make_pair(&iterator_in_list_to_update->second, false); - } + list.splice(list.end(), list, iterator_in_list_to_update); + iterator_in_list_to_update = --list.end(); + + return std::make_pair(&iterator_in_list_to_update->second, false); } value_type & operator[](const key_type & key) diff --git a/src/Common/getNumberOfCPUCoresToUse.cpp b/src/Common/getNumberOfCPUCoresToUse.cpp index 1a81e20d3b3..e6eff773a9d 100644 --- a/src/Common/getNumberOfCPUCoresToUse.cpp +++ b/src/Common/getNumberOfCPUCoresToUse.cpp @@ -26,8 +26,7 @@ int32_t readFrom(const std::filesystem::path & filename, int default_value) int idata; if (infile >> idata) return idata; - else - return default_value; + return default_value; } /// Try to look at cgroups limit if it is available. diff --git a/src/Common/memcmpSmall.h b/src/Common/memcmpSmall.h index 103eabb5b8d..a80f0872a9f 100644 --- a/src/Common/memcmpSmall.h +++ b/src/Common/memcmpSmall.h @@ -359,7 +359,7 @@ inline int memcmpSmallLikeZeroPaddedAllowOverflow15(const Char * a, size_t a_siz { return 0; } - else if (a_size > b_size) + if (a_size > b_size) { max_size = a_size; longest = a; diff --git a/src/Common/memory.h b/src/Common/memory.h index d673f954fb2..11b8e7dfd3a 100644 --- a/src/Common/memory.h +++ b/src/Common/memory.h @@ -46,10 +46,8 @@ inline ALWAYS_INLINE void * newImpl(std::size_t size, TAlign... align) ProfileEvents::increment(ProfileEvents::GWPAsanAllocateSuccess); return ptr; } - else - { - ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); - } + + ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); } else { @@ -58,11 +56,8 @@ inline ALWAYS_INLINE void * newImpl(std::size_t size, TAlign... align) ProfileEvents::increment(ProfileEvents::GWPAsanAllocateSuccess); return ptr; } - else - { - ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); - } + ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); } } #endif @@ -90,10 +85,8 @@ inline ALWAYS_INLINE void * newNoExcept(std::size_t size) noexcept ProfileEvents::increment(ProfileEvents::GWPAsanAllocateSuccess); return ptr; } - else - { - ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); - } + + ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); } #endif return malloc(size); @@ -109,10 +102,8 @@ inline ALWAYS_INLINE void * newNoExcept(std::size_t size, std::align_val_t align ProfileEvents::increment(ProfileEvents::GWPAsanAllocateSuccess); return ptr; } - else - { - ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); - } + + ProfileEvents::increment(ProfileEvents::GWPAsanAllocateFailed); } #endif return aligned_alloc(static_cast(align), size); diff --git a/src/Common/mysqlxx/Pool.cpp b/src/Common/mysqlxx/Pool.cpp index 546e9e91dc7..d61f8e751d0 100644 --- a/src/Common/mysqlxx/Pool.cpp +++ b/src/Common/mysqlxx/Pool.cpp @@ -388,10 +388,8 @@ Pool::Connection * Pool::allocConnection(bool dont_throw_if_failed_first_time) { throw; } - else - { - return nullptr; - } + + return nullptr; } connections.push_back(conn_ptr.get()); diff --git a/src/Common/mysqlxx/PoolFactory.cpp b/src/Common/mysqlxx/PoolFactory.cpp index 77a549b7a11..58b4633d84e 100644 --- a/src/Common/mysqlxx/PoolFactory.cpp +++ b/src/Common/mysqlxx/PoolFactory.cpp @@ -70,31 +70,30 @@ PoolWithFailover PoolFactory::get(const Poco::Util::AbstractConfiguration & conf { std::lock_guard lock(impl->mutex); - if (auto entry = impl->pools.find(config_name); entry != impl->pools.end()) + auto entry = impl->pools.find(config_name); + if (entry != impl->pools.end()) { return *(entry->second); } - else - { - std::string entry_name = getPoolEntryName(config, config_name); - if (auto id = impl->pools_by_ids.find(entry_name); id != impl->pools_by_ids.end()) - { - entry = impl->pools.find(id->second); - std::shared_ptr pool = entry->second; - impl->pools.insert_or_assign(config_name, pool); - return *pool; - } - auto pool = std::make_shared(config, config_name, default_connections, max_connections, max_tries); - // Check the pool will be shared - if (!entry_name.empty()) - { - // Store shared pool - impl->pools.insert_or_assign(config_name, pool); - impl->pools_by_ids.insert_or_assign(entry_name, config_name); - } + std::string entry_name = getPoolEntryName(config, config_name); + if (auto id = impl->pools_by_ids.find(entry_name); id != impl->pools_by_ids.end()) + { + entry = impl->pools.find(id->second); + std::shared_ptr pool = entry->second; + impl->pools.insert_or_assign(config_name, pool); return *pool; } + + auto pool = std::make_shared(config, config_name, default_connections, max_connections, max_tries); + // Check the pool will be shared + if (!entry_name.empty()) + { + // Store shared pool + impl->pools.insert_or_assign(config_name, pool); + impl->pools_by_ids.insert_or_assign(entry_name, config_name); + } + return *pool; } void PoolFactory::reset() diff --git a/src/Common/mysqlxx/PoolWithFailover.cpp b/src/Common/mysqlxx/PoolWithFailover.cpp index df2e3b61c33..bbf077d3aa1 100644 --- a/src/Common/mysqlxx/PoolWithFailover.cpp +++ b/src/Common/mysqlxx/PoolWithFailover.cpp @@ -213,7 +213,5 @@ PoolWithFailover::Entry PoolWithFailover::get() if (replicas_by_priority.size() > 1) throw DB::Exception(DB::ErrorCodes::ALL_CONNECTION_TRIES_FAILED, "Connections to all mysql replicas failed: {}", message.str()); - else - throw DB::Exception(DB::ErrorCodes::ALL_CONNECTION_TRIES_FAILED, "Connections to mysql failed: {}", message.str()); - + throw DB::Exception(DB::ErrorCodes::ALL_CONNECTION_TRIES_FAILED, "Connections to mysql failed: {}", message.str()); } diff --git a/src/Common/mysqlxx/mysqlxx/Pool.h b/src/Common/mysqlxx/mysqlxx/Pool.h index f1ef81e28dd..2889140dcb2 100644 --- a/src/Common/mysqlxx/mysqlxx/Pool.h +++ b/src/Common/mysqlxx/mysqlxx/Pool.h @@ -103,8 +103,7 @@ public: { if (pool) return pool->getDescription(); - else - return "pool is null"; + return "pool is null"; } void disconnect(); diff --git a/src/Common/mysqlxx/mysqlxx/Value.h b/src/Common/mysqlxx/mysqlxx/Value.h index 892e5a19d93..6fa2fed03d4 100644 --- a/src/Common/mysqlxx/mysqlxx/Value.h +++ b/src/Common/mysqlxx/mysqlxx/Value.h @@ -153,7 +153,7 @@ private: (m_data[5] - '0') * 10 + (m_data[6] - '0'), (m_data[8] - '0') * 10 + (m_data[9] - '0')); } - else if (m_length == 19) + if (m_length == 19) { return date_lut.makeDateTime( (m_data[0] - '0') * 1000 + (m_data[1] - '0') * 100 + (m_data[2] - '0') * 10 + (m_data[3] - '0'), @@ -163,10 +163,7 @@ private: (m_data[14] - '0') * 10 + (m_data[15] - '0'), (m_data[17] - '0') * 10 + (m_data[18] - '0')); } - else - throwException("Cannot parse DateTime"); - - return 0; /// avoid warning. /// NOLINT + throwException("Cannot parse DateTime"); } @@ -181,8 +178,7 @@ private: (m_data[5] - '0') * 10 + (m_data[6] - '0'), (m_data[8] - '0') * 10 + (m_data[9] - '0')); } - else - throwException("Cannot parse Date"); + throwException("Cannot parse Date"); return 0; /// avoid warning. /// NOLINT } @@ -201,8 +197,7 @@ private: if (checkDateTime()) return getDateTimeImpl(); - else - return getIntImpl(); + return getIntImpl(); } @@ -213,11 +208,9 @@ private: if (checkDateTime()) return getDateImpl(); - else - { - const auto & date_lut = DateLUT::instance(); - return date_lut.toDate(getIntImpl()); - } + + const auto & date_lut = DateLUT::instance(); + return date_lut.toDate(getIntImpl()); } diff --git a/src/Common/parseAddress.cpp b/src/Common/parseAddress.cpp index 339c015ca9c..53cba7c5039 100644 --- a/src/Common/parseAddress.cpp +++ b/src/Common/parseAddress.cpp @@ -50,13 +50,13 @@ std::pair parseAddress(const std::string & str, UInt16 defa } return { std::string(begin, port - 1), port_number }; } - else if (default_port) + if (default_port) { - return { str, default_port }; + return {str, default_port}; } - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, - "The address passed to function parseAddress doesn't contain port number and no 'default_port' was passed"); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "The address passed to function parseAddress doesn't contain port number and no 'default_port' was passed"); } } diff --git a/src/Common/remapExecutable.cpp b/src/Common/remapExecutable.cpp index 911447d3adc..ed6a614141b 100644 --- a/src/Common/remapExecutable.cpp +++ b/src/Common/remapExecutable.cpp @@ -2,9 +2,9 @@ #if defined(OS_LINUX) && defined(__amd64__) && defined(__SSE2__) && !defined(SANITIZER) && defined(NDEBUG) -#include +#include #include -#include +#include #include #include diff --git a/src/Common/typeid_cast.h b/src/Common/typeid_cast.h index f1ded97a9f1..f825c1d7125 100644 --- a/src/Common/typeid_cast.h +++ b/src/Common/typeid_cast.h @@ -41,8 +41,7 @@ To typeid_cast(From * from) noexcept { if ((typeid(From) == typeid(std::remove_pointer_t)) || (from && typeid(*from) == typeid(std::remove_pointer_t))) return static_cast(from); - else - return nullptr; + return nullptr; } namespace detail @@ -69,6 +68,5 @@ To typeid_cast(const std::shared_ptr & from) noexcept { if ((typeid(From) == typeid(typename To::element_type)) || (from && typeid(*from) == typeid(typename To::element_type))) return std::static_pointer_cast(from); - else - return nullptr; + return nullptr; } diff --git a/src/Compression/CompressedReadBufferBase.cpp b/src/Compression/CompressedReadBufferBase.cpp index 907e87a6d30..2b65f2d690c 100644 --- a/src/Compression/CompressedReadBufferBase.cpp +++ b/src/Compression/CompressedReadBufferBase.cpp @@ -255,11 +255,9 @@ size_t CompressedReadBufferBase::readCompressedDataBlockForAsynchronous(size_t & ProfileEvents::increment(ProfileEvents::ReadCompressedBytes, size_compressed_without_checksum + sizeof(Checksum)); return size_compressed_without_checksum + sizeof(Checksum); } - else - { - compressed_in->position() -= (sizeof(Checksum) + header_size); - return 0; - } + + compressed_in->position() -= (sizeof(Checksum) + header_size); + return 0; } static void readHeaderAndGetCodec(const char * compressed_buffer, size_t size_decompressed, CompressionCodecPtr & codec, diff --git a/src/Compression/CompressionCodecDeflateQpl.cpp b/src/Compression/CompressionCodecDeflateQpl.cpp index a9654e60006..30085762c00 100644 --- a/src/Compression/CompressionCodecDeflateQpl.cpp +++ b/src/Compression/CompressionCodecDeflateQpl.cpp @@ -119,8 +119,7 @@ qpl_job * DeflateQplJobHWPool::acquireJob(UInt32 & job_id) assert(index < max_hw_jobs); return reinterpret_cast(hw_jobs_buffer.get() + index * per_job_size); } - else - return nullptr; + return nullptr; } void DeflateQplJobHWPool::releaseJob(UInt32 job_id) @@ -184,18 +183,21 @@ Int32 HardwareCodecDeflateQpl::doCompressData(const char * source, UInt32 source job_ptr->available_out = dest_size; job_ptr->flags = QPL_FLAG_FIRST | QPL_FLAG_DYNAMIC_HUFFMAN | QPL_FLAG_LAST | QPL_FLAG_OMIT_VERIFY; - if (auto status = qpl_execute_job(job_ptr); status == QPL_STS_OK) + auto status = qpl_execute_job(job_ptr); + if (status == QPL_STS_OK) { compressed_size = job_ptr->total_out; DeflateQplJobHWPool::instance().releaseJob(job_id); return compressed_size; } - else - { - LOG_WARNING(log, "DeflateQpl HW codec failed, falling back to SW codec. (Details: doCompressData->qpl_execute_job with error code: {} - please refer to qpl_status in ./contrib/qpl/include/qpl/c_api/status.h)", static_cast(status)); - DeflateQplJobHWPool::instance().releaseJob(job_id); - return RET_ERROR; - } + + LOG_WARNING( + log, + "DeflateQpl HW codec failed, falling back to SW codec. (Details: doCompressData->qpl_execute_job with error code: {} - please " + "refer to qpl_status in ./contrib/qpl/include/qpl/c_api/status.h)", + static_cast(status)); + DeflateQplJobHWPool::instance().releaseJob(job_id); + return RET_ERROR; } Int32 HardwareCodecDeflateQpl::doDecompressDataSynchronous(const char * source, UInt32 source_size, char * dest, UInt32 uncompressed_size) @@ -261,17 +263,20 @@ Int32 HardwareCodecDeflateQpl::doDecompressDataAsynchronous(const char * source, job_ptr->available_out = uncompressed_size; job_ptr->flags = QPL_FLAG_FIRST | QPL_FLAG_LAST; - if (auto status = qpl_submit_job(job_ptr); status == QPL_STS_OK) + auto status = qpl_submit_job(job_ptr); + if (status == QPL_STS_OK) { decomp_async_job_map.insert({job_id, job_ptr}); return job_id; } - else - { - DeflateQplJobHWPool::instance().releaseJob(job_id); - LOG_WARNING(log, "DeflateQpl HW codec failed, falling back to SW codec. (Details: doDecompressDataAsynchronous->qpl_submit_job with error code: {} - please refer to qpl_status in ./contrib/qpl/include/qpl/c_api/status.h)", static_cast(status)); - return RET_ERROR; - } + + DeflateQplJobHWPool::instance().releaseJob(job_id); + LOG_WARNING( + log, + "DeflateQpl HW codec failed, falling back to SW codec. (Details: doDecompressDataAsynchronous->qpl_submit_job with error code: {} " + "- please refer to qpl_status in ./contrib/qpl/include/qpl/c_api/status.h)", + static_cast(status)); + return RET_ERROR; } void HardwareCodecDeflateQpl::flushAsynchronousDecompressRequests() diff --git a/src/Compression/CompressionCodecDelta.cpp b/src/Compression/CompressionCodecDelta.cpp index 924cdd9a60f..680f93a61b6 100644 --- a/src/Compression/CompressionCodecDelta.cpp +++ b/src/Compression/CompressionCodecDelta.cpp @@ -180,9 +180,10 @@ UInt8 getDeltaBytesSize(const IDataType * column_type) size_t max_size = column_type->getSizeOfValueInMemory(); if (max_size == 1 || max_size == 2 || max_size == 4 || max_size == 8) return static_cast(max_size); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Codec Delta is only applicable for data types of size 1, 2, 4, 8 bytes. Given type {}", - column_type->getName()); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Codec Delta is only applicable for data types of size 1, 2, 4, 8 bytes. Given type {}", + column_type->getName()); } } diff --git a/src/Compression/CompressionCodecDoubleDelta.cpp b/src/Compression/CompressionCodecDoubleDelta.cpp index cbd8cd57a62..722e23f51e6 100644 --- a/src/Compression/CompressionCodecDoubleDelta.cpp +++ b/src/Compression/CompressionCodecDoubleDelta.cpp @@ -233,22 +233,20 @@ WriteSpec getDeltaWriteSpec(const T & value) { return WriteSpec{2, 0b10, 7}; } - else if (value > -255 && value < 256) + if (value > -255 && value < 256) { return WriteSpec{3, 0b110, 9}; } - else if (value > -2047 && value < 2048) + if (value > -2047 && value < 2048) { return WriteSpec{4, 0b1110, 12}; } - else if (value > std::numeric_limits::min() && value < std::numeric_limits::max()) + if (value > std::numeric_limits::min() && value < std::numeric_limits::max()) { return WriteSpec{5, 0b11110, 32}; } - else - { - return WriteSpec{5, 0b11111, 64}; - } + + return WriteSpec{5, 0b11111, 64}; } WriteSpec getDeltaMaxWriteSpecByteSize(UInt8 data_bytes_size) @@ -452,9 +450,10 @@ UInt8 getDataBytesSize(const IDataType * column_type) size_t max_size = column_type->getSizeOfValueInMemory(); if (max_size == 1 || max_size == 2 || max_size == 4 || max_size == 8) return static_cast(max_size); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Codec DoubleDelta is only applicable for data types of size 1, 2, 4, 8 bytes. Given type {}", - column_type->getName()); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Codec DoubleDelta is only applicable for data types of size 1, 2, 4, 8 bytes. Given type {}", + column_type->getName()); } } diff --git a/src/Compression/CompressionCodecEncrypted.cpp b/src/Compression/CompressionCodecEncrypted.cpp index d9721d90655..b41abefa852 100644 --- a/src/Compression/CompressionCodecEncrypted.cpp +++ b/src/Compression/CompressionCodecEncrypted.cpp @@ -30,10 +30,9 @@ EncryptionMethod toEncryptionMethod(const std::string & name) { if (name == "AES_128_GCM_SIV") return AES_128_GCM_SIV; - else if (name == "AES_256_GCM_SIV") + if (name == "AES_256_GCM_SIV") return AES_256_GCM_SIV; - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown encryption method. Got {}", name); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown encryption method. Got {}", name); } namespace @@ -44,10 +43,9 @@ String getMethodName(EncryptionMethod Method) { if (Method == AES_128_GCM_SIV) return "AES_128_GCM_SIV"; - else if (Method == AES_256_GCM_SIV) + if (Method == AES_256_GCM_SIV) return "AES_256_GCM_SIV"; - else - return ""; + return ""; } /// Get method code (used for codec, to understand which one we are using) @@ -55,10 +53,9 @@ uint8_t getMethodCode(EncryptionMethod Method) { if (Method == AES_128_GCM_SIV) return static_cast(CompressionMethodByte::AES_128_GCM_SIV); - else if (Method == AES_256_GCM_SIV) + if (Method == AES_256_GCM_SIV) return static_cast(CompressionMethodByte::AES_256_GCM_SIV); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown encryption method. Got {}", getMethodName(Method)); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown encryption method. Got {}", getMethodName(Method)); } } // end of namespace @@ -90,10 +87,9 @@ UInt64 methodKeySize(EncryptionMethod Method) { if (Method == AES_128_GCM_SIV) return 16; - else if (Method == AES_256_GCM_SIV) + if (Method == AES_256_GCM_SIV) return 32; - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown encryption method. Got {}", getMethodName(Method)); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown encryption method. Got {}", getMethodName(Method)); } /// Get human-readable string representation of last error @@ -310,11 +306,9 @@ inline char* writeNonce(const String& nonce, char* dest) dest += copied_symbols; return dest; } - else - { - *dest = 0; - return ++dest; - } + + *dest = 0; + return ++dest; } /// Firstly, read a byte, which shows if the nonce will be put in text (if it was defined in config) diff --git a/src/Compression/CompressionCodecFPC.cpp b/src/Compression/CompressionCodecFPC.cpp index 2a6dfda7b5c..f52ebac47ec 100644 --- a/src/Compression/CompressionCodecFPC.cpp +++ b/src/Compression/CompressionCodecFPC.cpp @@ -290,17 +290,16 @@ private: size_t importChunk(std::span values, std::span current_chunk) { - if (auto chunk_view = std::as_writable_bytes(current_chunk); chunk_view.size() <= values.size()) + auto chunk_view = std::as_writable_bytes(current_chunk); + if (chunk_view.size() <= values.size()) { memcpy(chunk_view.data(), values.data(), chunk_view.size()); return chunk_view.size() / VALUE_SIZE; } - else - { - memset(chunk_view.data(), 0, chunk_view.size()); - memcpy(chunk_view.data(), values.data(), values.size()); - return ceilBytesToEvenValues(values.size()); - } + + memset(chunk_view.data(), 0, chunk_view.size()); + memcpy(chunk_view.data(), values.data(), values.size()); + return ceilBytesToEvenValues(values.size()); } void exportChunk(std::span current_chunk) diff --git a/src/Compression/CompressionCodecGCD.cpp b/src/Compression/CompressionCodecGCD.cpp index 59e11f896f0..7e1b8f48f34 100644 --- a/src/Compression/CompressionCodecGCD.cpp +++ b/src/Compression/CompressionCodecGCD.cpp @@ -256,9 +256,10 @@ UInt8 getGCDBytesSize(const IDataType * column_type) size_t max_size = column_type->getSizeOfValueInMemory(); if (max_size == 1 || max_size == 2 || max_size == 4 || max_size == 8 || max_size == 16 || max_size == 32) return static_cast(max_size); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Codec GCD is only applicable for data types of size 1, 2, 4, 8, 16, 32 bytes. Given type {}", - column_type->getName()); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Codec GCD is only applicable for data types of size 1, 2, 4, 8, 16, 32 bytes. Given type {}", + column_type->getName()); } } @@ -273,7 +274,7 @@ void registerCodecGCD(CompressionCodecFactory & factory) if (arguments && !arguments->children.empty()) throw Exception(ErrorCodes::ILLEGAL_SYNTAX_FOR_CODEC_TYPE, "GCD codec must have 0 parameters, given {}", arguments->children.size()); - else if (column_type) + if (column_type) gcd_bytes_size = getGCDBytesSize(column_type); return std::make_shared(gcd_bytes_size); diff --git a/src/Compression/CompressionCodecGorilla.cpp b/src/Compression/CompressionCodecGorilla.cpp index 29148c5cdff..8c7cd37f17c 100644 --- a/src/Compression/CompressionCodecGorilla.cpp +++ b/src/Compression/CompressionCodecGorilla.cpp @@ -346,9 +346,10 @@ UInt8 getDataBytesSize(const IDataType * column_type) size_t max_size = column_type->getSizeOfValueInMemory(); if (max_size == 1 || max_size == 2 || max_size == 4 || max_size == 8) return static_cast(max_size); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Codec Gorilla is only applicable for data types of size 1, 2, 4, 8 bytes. Given type {}", - column_type->getName()); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Codec Gorilla is only applicable for data types of size 1, 2, 4, 8 bytes. Given type {}", + column_type->getName()); } } diff --git a/src/Compression/CompressionCodecT64.cpp b/src/Compression/CompressionCodecT64.cpp index 8040e2c4d50..634142503f5 100644 --- a/src/Compression/CompressionCodecT64.cpp +++ b/src/Compression/CompressionCodecT64.cpp @@ -451,11 +451,9 @@ UInt32 getValuableBitsNumber(Int64 min, Int64 max) { if (min + max >= 0) return getValuableBitsNumber(0ull, static_cast(max)) + 1; - else - return getValuableBitsNumber(0ull, static_cast(~min)) + 1; + return getValuableBitsNumber(0ull, static_cast(~min)) + 1; } - else - return getValuableBitsNumber(static_cast(min), static_cast(max)); + return getValuableBitsNumber(static_cast(min), static_cast(max)); } diff --git a/src/Compression/CompressionFactory.cpp b/src/Compression/CompressionFactory.cpp index ac00f571568..fb4581f22b4 100644 --- a/src/Compression/CompressionFactory.cpp +++ b/src/Compression/CompressionFactory.cpp @@ -39,11 +39,9 @@ CompressionCodecPtr CompressionCodecFactory::get(const String & family_name, std auto level_literal = std::make_shared(static_cast(*level)); return get(makeASTFunction("CODEC", makeASTFunction(Poco::toUpper(family_name), level_literal)), {}); } - else - { - auto identifier = std::make_shared(Poco::toUpper(family_name)); - return get(makeASTFunction("CODEC", identifier), {}); - } + + auto identifier = std::make_shared(Poco::toUpper(family_name)); + return get(makeASTFunction("CODEC", identifier), {}); } CompressionCodecPtr CompressionCodecFactory::get(const String & compression_codec) const @@ -96,10 +94,9 @@ CompressionCodecPtr CompressionCodecFactory::get( if (codecs.size() == 1) return codecs.back(); - else if (codecs.size() > 1) + if (codecs.size() > 1) return std::make_shared(codecs); - else - return std::make_shared(); + return std::make_shared(); } throw Exception(ErrorCodes::UNEXPECTED_AST_STRUCTURE, "Unexpected AST structure for compression codec: {}", queryToString(ast)); diff --git a/src/Compression/CompressionFactoryAdditions.cpp b/src/Compression/CompressionFactoryAdditions.cpp index f4d993f628e..a54169d4524 100644 --- a/src/Compression/CompressionFactoryAdditions.cpp +++ b/src/Compression/CompressionFactoryAdditions.cpp @@ -262,10 +262,8 @@ ASTPtr CompressionCodecFactory::validateCodecAndGetPreprocessedAST( result->arguments = codecs_descriptions; return result; } - else - { - return ast; - } + + return ast; } throw Exception(ErrorCodes::UNKNOWN_CODEC, "Unknown codec family: {}", queryToString(ast)); diff --git a/src/Compression/ICompressionCodec.cpp b/src/Compression/ICompressionCodec.cpp index b4cd6864030..418667a3a8f 100644 --- a/src/Compression/ICompressionCodec.cpp +++ b/src/Compression/ICompressionCodec.cpp @@ -65,8 +65,8 @@ ASTPtr ICompressionCodec::getCodecDesc() const /// If it has exactly one argument, than it's single codec, return it if (arguments->children.size() == 1) return arguments->children[0]; - else /// Otherwise we have multiple codecs and return them as expression list - return arguments; + /// Otherwise we have multiple codecs and return them as expression list + return arguments; } UInt64 ICompressionCodec::getHash() const diff --git a/src/Compression/LZ4_decompress_faster.cpp b/src/Compression/LZ4_decompress_faster.cpp index c5bc6eb67d5..cce8319d0ca 100644 --- a/src/Compression/LZ4_decompress_faster.cpp +++ b/src/Compression/LZ4_decompress_faster.cpp @@ -680,10 +680,8 @@ bool decompress( return success; } - else - { - return decompressImpl<8, false>(source, dest, source_size, dest_size); - } + + return decompressImpl<8, false>(source, dest, source_size, dest_size); } diff --git a/src/Compression/LZ4_decompress_faster.h b/src/Compression/LZ4_decompress_faster.h index 08744755916..14ef00647fb 100644 --- a/src/Compression/LZ4_decompress_faster.h +++ b/src/Compression/LZ4_decompress_faster.h @@ -82,8 +82,7 @@ struct PerformanceStatistics if (adjustedCount() < 2) return adjustedCount() - 1; - else - return std::normal_distribution<>(mean(), sigma())(stat_rng); + return std::normal_distribution<>(mean(), sigma())(stat_rng); } }; @@ -118,8 +117,7 @@ struct PerformanceStatistics return std::min_element(samples, samples + max_method) - samples; } - else - return choose_method; + return choose_method; } PerformanceStatistics() = default; diff --git a/src/Coordination/Changelog.cpp b/src/Coordination/Changelog.cpp index 89034951f94..c96f17d7064 100644 --- a/src/Coordination/Changelog.cpp +++ b/src/Coordination/Changelog.cpp @@ -1687,7 +1687,7 @@ try initialized = true; return; } - else if (changelog_description.from_log_index > start_to_read_from) + if (changelog_description.from_log_index > start_to_read_from) { /// We don't have required amount of reserved logs, but nothing was lost. LOG_WARNING( diff --git a/src/Coordination/FourLetterCommand.cpp b/src/Coordination/FourLetterCommand.cpp index 30dfaee23c8..1e9f2c96ea0 100644 --- a/src/Coordination/FourLetterCommand.cpp +++ b/src/Coordination/FourLetterCommand.cpp @@ -236,17 +236,15 @@ void FourLetterCommandFactory::initializeAllowList(KeeperDispatcher & keeper_dis allow_list.push_back(ALLOW_LIST_ALL); return; } + + if (commands.contains(IFourLetterCommand::toCode(token))) + { + allow_list.push_back(IFourLetterCommand::toCode(token)); + } else { - if (commands.contains(IFourLetterCommand::toCode(token))) - { - allow_list.push_back(IFourLetterCommand::toCode(token)); - } - else - { - auto log = getLogger("FourLetterCommandFactory"); - LOG_WARNING(log, "Find invalid keeper 4lw command {} when initializing, ignore it.", token); - } + auto log = getLogger("FourLetterCommandFactory"); + LOG_WARNING(log, "Find invalid keeper 4lw command {} when initializing, ignore it.", token); } } } @@ -534,8 +532,7 @@ String IsReadOnlyCommand::run() { if (keeper_dispatcher.isObserver()) return "ro"; - else - return "rw"; + return "rw"; } String RecoveryCommand::run() diff --git a/src/Coordination/KeeperContext.cpp b/src/Coordination/KeeperContext.cpp index 6ae4a1ee61d..999e517cc0b 100644 --- a/src/Coordination/KeeperContext.cpp +++ b/src/Coordination/KeeperContext.cpp @@ -138,8 +138,7 @@ KeeperContext::Storage KeeperContext::getRocksDBPathFromConfig(const Poco::Util: if (standalone_keeper) return create_local_disk(std::filesystem::path{config.getString("path", KEEPER_DEFAULT_PATH)} / "rocksdb"); - else - return create_local_disk(std::filesystem::path{config.getString("path", DBMS_DEFAULT_PATH)} / "coordination/rocksdb"); + return create_local_disk(std::filesystem::path{config.getString("path", DBMS_DEFAULT_PATH)} / "coordination/rocksdb"); } void KeeperContext::initialize(const Poco::Util::AbstractConfiguration & config, KeeperDispatcher * dispatcher_) @@ -428,8 +427,7 @@ KeeperContext::Storage KeeperContext::getLogsPathFromConfig(const Poco::Util::Ab if (standalone_keeper) return create_local_disk(std::filesystem::path{config.getString("path", KEEPER_DEFAULT_PATH)} / "logs"); - else - return create_local_disk(std::filesystem::path{config.getString("path", DBMS_DEFAULT_PATH)} / "coordination/logs"); + return create_local_disk(std::filesystem::path{config.getString("path", DBMS_DEFAULT_PATH)} / "coordination/logs"); } KeeperContext::Storage KeeperContext::getSnapshotsPathFromConfig(const Poco::Util::AbstractConfiguration & config) const @@ -456,8 +454,7 @@ KeeperContext::Storage KeeperContext::getSnapshotsPathFromConfig(const Poco::Uti if (standalone_keeper) return create_local_disk(std::filesystem::path{config.getString("path", KEEPER_DEFAULT_PATH)} / "snapshots"); - else - return create_local_disk(std::filesystem::path{config.getString("path", DBMS_DEFAULT_PATH)} / "coordination/snapshots"); + return create_local_disk(std::filesystem::path{config.getString("path", DBMS_DEFAULT_PATH)} / "coordination/snapshots"); } KeeperContext::Storage KeeperContext::getStatePathFromConfig(const Poco::Util::AbstractConfiguration & config) const @@ -486,8 +483,7 @@ KeeperContext::Storage KeeperContext::getStatePathFromConfig(const Poco::Util::A if (standalone_keeper) return create_local_disk(std::filesystem::path{config.getString("path", KEEPER_DEFAULT_PATH)}); - else - return create_local_disk(std::filesystem::path{config.getString("path", DBMS_DEFAULT_PATH)} / "coordination"); + return create_local_disk(std::filesystem::path{config.getString("path", DBMS_DEFAULT_PATH)} / "coordination"); } void KeeperContext::initializeFeatureFlags(const Poco::Util::AbstractConfiguration & config) diff --git a/src/Coordination/KeeperDispatcher.cpp b/src/Coordination/KeeperDispatcher.cpp index 8d7c6543c6e..97c57b65a05 100644 --- a/src/Coordination/KeeperDispatcher.cpp +++ b/src/Coordination/KeeperDispatcher.cpp @@ -63,7 +63,7 @@ bool checkIfRequestIncreaseMem(const Coordination::ZooKeeperRequestPtr & request { return true; } - else if (request->getOpNum() == Coordination::OpNum::Multi) + if (request->getOpNum() == Coordination::OpNum::Multi) { Coordination::ZooKeeperMultiRequest & multi_req = dynamic_cast(*request); Int64 memory_delta = 0; @@ -73,27 +73,26 @@ bool checkIfRequestIncreaseMem(const Coordination::ZooKeeperRequestPtr & request switch (sub_zk_request->getOpNum()) { case Coordination::OpNum::Create: - case Coordination::OpNum::CreateIfNotExists: - { - Coordination::ZooKeeperCreateRequest & create_req = dynamic_cast(*sub_zk_request); + case Coordination::OpNum::CreateIfNotExists: { + Coordination::ZooKeeperCreateRequest & create_req + = dynamic_cast(*sub_zk_request); memory_delta += create_req.bytesSize(); break; } - case Coordination::OpNum::Set: - { + case Coordination::OpNum::Set: { Coordination::ZooKeeperSetRequest & set_req = dynamic_cast(*sub_zk_request); memory_delta += set_req.bytesSize(); break; } - case Coordination::OpNum::Remove: - { - Coordination::ZooKeeperRemoveRequest & remove_req = dynamic_cast(*sub_zk_request); + case Coordination::OpNum::Remove: { + Coordination::ZooKeeperRemoveRequest & remove_req + = dynamic_cast(*sub_zk_request); memory_delta -= remove_req.bytesSize(); break; } - case Coordination::OpNum::RemoveRecursive: - { - Coordination::ZooKeeperRemoveRecursiveRequest & remove_req = dynamic_cast(*sub_zk_request); + case Coordination::OpNum::RemoveRecursive: { + Coordination::ZooKeeperRemoveRecursiveRequest & remove_req + = dynamic_cast(*sub_zk_request); memory_delta -= remove_req.bytesSize(); break; } diff --git a/src/Coordination/KeeperServer.cpp b/src/Coordination/KeeperServer.cpp index 57b15245f19..765adf14176 100644 --- a/src/Coordination/KeeperServer.cpp +++ b/src/Coordination/KeeperServer.cpp @@ -1019,7 +1019,7 @@ KeeperServer::ConfigUpdateState KeeperServer::applyConfigUpdate( resp->get(); return resp->get_accepted() ? Accepted : Declined; } - else if (const auto * remove = std::get_if(&action)) + if (const auto * remove = std::get_if(&action)) { // This corner case is the most problematic. Issue follows: if we agree on a number // of commands but don't commit them on leader, and then issue a leadership change via @@ -1049,16 +1049,16 @@ KeeperServer::ConfigUpdateState KeeperServer::applyConfigUpdate( resp->get(); return resp->get_accepted() ? Accepted : Declined; } - else if (const auto * update = std::get_if(&action)) + if (const auto * update = std::get_if(&action)) { - if (auto ptr = raft_instance->get_srv_config(update->id); ptr == nullptr) - throw Exception(ErrorCodes::RAFT_ERROR, - "Attempt to apply {} but server is not present in Raft", - action); - else if (ptr->get_priority() == update->priority) + auto ptr = raft_instance->get_srv_config(update->id); + + if (ptr == nullptr) + throw Exception(ErrorCodes::RAFT_ERROR, "Attempt to apply {} but server is not present in Raft", action); + if (ptr->get_priority() == update->priority) return Accepted; - raft_instance->set_priority(update->id, update->priority, /*broadcast on live leader*/true); + raft_instance->set_priority(update->id, update->priority, /*broadcast on live leader*/ true); return Accepted; } std::unreachable(); diff --git a/src/Coordination/KeeperSnapshotManager.cpp b/src/Coordination/KeeperSnapshotManager.cpp index 231f50c7f81..1195b2d4150 100644 --- a/src/Coordination/KeeperSnapshotManager.cpp +++ b/src/Coordination/KeeperSnapshotManager.cpp @@ -410,14 +410,13 @@ void KeeperStorageSnapshot::deserialize(SnapshotDeserializationResultsecond; + return request_it->second; } } } @@ -600,9 +599,12 @@ bool KeeperStateMachine::apply_snapshot(nuraft::snapshot & s) s.get_last_log_idx(), latest_snapshot_meta->get_last_log_idx()); } - else if (s.get_last_log_idx() < latest_snapshot_meta->get_last_log_idx()) + if (s.get_last_log_idx() < latest_snapshot_meta->get_last_log_idx()) { - LOG_INFO(log, "A snapshot with a larger last log index ({}) was created, skipping applying this snapshot", latest_snapshot_meta->get_last_log_idx()); + LOG_INFO( + log, + "A snapshot with a larger last log index ({}) was created, skipping applying this snapshot", + latest_snapshot_meta->get_last_log_idx()); return true; } diff --git a/src/Coordination/KeeperStateManager.cpp b/src/Coordination/KeeperStateManager.cpp index 15f520154b1..93131c09f59 100644 --- a/src/Coordination/KeeperStateManager.cpp +++ b/src/Coordination/KeeperStateManager.cpp @@ -157,22 +157,21 @@ KeeperStateManager::parseServersConfiguration(const Poco::Util::AbstractConfigur check_duplicated_hostnames[endpoint], new_server_id); } - else + + /// Fullscan to check duplicated ids + for (const auto & [id_endpoint, id] : check_duplicated_hostnames) { - /// Fullscan to check duplicated ids - for (const auto & [id_endpoint, id] : check_duplicated_hostnames) - { - if (new_server_id == id) - throw Exception( - ErrorCodes::RAFT_ERROR, - "Raft config contains duplicate ids: id {} has been already added with endpoint {}, " - "but going to add it one more time with endpoint {}", - id, - id_endpoint, - endpoint); - } - check_duplicated_hostnames.emplace(endpoint, new_server_id); + if (new_server_id == id) + throw Exception( + ErrorCodes::RAFT_ERROR, + "Raft config contains duplicate ids: id {} has been already added with endpoint {}, " + "but going to add it one more time with endpoint {}", + id, + id_endpoint, + endpoint); } + check_duplicated_hostnames.emplace(endpoint, new_server_id); + auto peer_config = nuraft::cs_new(new_server_id, 0, endpoint, "", !can_become_leader, priority); if (my_server_id == new_server_id) diff --git a/src/Coordination/KeeperStorage.cpp b/src/Coordination/KeeperStorage.cpp index c1ffd2f0ef5..7d6f5dfa5dc 100644 --- a/src/Coordination/KeeperStorage.cpp +++ b/src/Coordination/KeeperStorage.cpp @@ -1407,7 +1407,7 @@ std::list preprocess( if (parent_node == nullptr) return {typename Storage::Delta{zxid, Coordination::Error::ZNONODE}}; - else if (parent_node->stats.isEphemeral()) + if (parent_node->stats.isEphemeral()) return {KeeperStorageBase::Delta{zxid, Coordination::Error::ZNOCHILDRENFOREPHEMERALS}}; std::string path_created = zk_request.path; @@ -1692,9 +1692,9 @@ std::list preprocess( } return {KeeperStorageBase::Delta{zxid, Coordination::Error::ZNONODE}}; } - else if (zk_request.version != -1 && zk_request.version != node->stats.version) + if (zk_request.version != -1 && zk_request.version != node->stats.version) return {KeeperStorageBase::Delta{zxid, Coordination::Error::ZBADVERSION}}; - else if (node->stats.numChildren() != 0) + if (node->stats.numChildren() != 0) return {KeeperStorageBase::Delta{zxid, Coordination::Error::ZNOTEMPTY}}; if (zk_request.restored_from_zookeeper_log) diff --git a/src/Coordination/RocksDBContainer.h b/src/Coordination/RocksDBContainer.h index 193e6d0b270..376ca894e1c 100644 --- a/src/Coordination/RocksDBContainer.h +++ b/src/Coordination/RocksDBContainer.h @@ -320,7 +320,7 @@ public: { return false; } - else if (status.IsNotFound()) + if (status.IsNotFound()) { status = rocksdb_ptr->Put(write_options, encoded_key, value.getEncodedString()); if (status.ok()) @@ -415,8 +415,7 @@ public: { if (!snapshot_mode) return std::make_pair(counter, current_version); - else - return std::make_pair(snapshot_size, current_version); + return std::make_pair(snapshot_size, current_version); } const_iterator begin() const diff --git a/src/Core/BackgroundSchedulePool.cpp b/src/Core/BackgroundSchedulePool.cpp index 4facdeb4631..2805121a1f6 100644 --- a/src/Core/BackgroundSchedulePool.cpp +++ b/src/Core/BackgroundSchedulePool.cpp @@ -342,12 +342,10 @@ void BackgroundSchedulePool::delayExecutionThreadFunction() delayed_tasks_cond_var.wait_for(lock, std::chrono::microseconds(min_time - current_time)); continue; } - else - { - /// We have a task ready for execution - found = true; - break; - } + + /// We have a task ready for execution + found = true; + break; } } diff --git a/src/Core/BaseSettings.h b/src/Core/BaseSettings.h index 110c062312c..f281267cab9 100644 --- a/src/Core/BaseSettings.h +++ b/src/Core/BaseSettings.h @@ -235,8 +235,7 @@ Field BaseSettings::get(std::string_view name) const const auto & accessor = Traits::Accessor::instance(); if (size_t index = accessor.find(name); index != static_cast(-1)) return accessor.getValue(*this, index); - else - return static_cast(getCustomSetting(name)); + return static_cast(getCustomSetting(name)); } template @@ -257,8 +256,7 @@ String BaseSettings::getString(std::string_view name) const const auto & accessor = Traits::Accessor::instance(); if (size_t index = accessor.find(name); index != static_cast(-1)) return accessor.getValueString(*this, index); - else - return getCustomSetting(name).toString(); + return getCustomSetting(name).toString(); } template @@ -381,10 +379,9 @@ const char * BaseSettings::getTypeName(std::string_view name) const const auto & accessor = Traits::Accessor::instance(); if (size_t index = accessor.find(name); index != static_cast(-1)) return accessor.getTypeName(index); - else if (tryGetCustomSetting(name)) + if (tryGetCustomSetting(name)) return "Custom"; - else - BaseSettingsHelpers::throwSettingNotFound(name); + BaseSettingsHelpers::throwSettingNotFound(name); } template @@ -394,10 +391,9 @@ const char * BaseSettings::getDescription(std::string_view name) const const auto & accessor = Traits::Accessor::instance(); if (size_t index = accessor.find(name); index != static_cast(-1)) return accessor.getDescription(index); - else if (tryGetCustomSetting(name)) + if (tryGetCustomSetting(name)) return "Custom"; - else - BaseSettingsHelpers::throwSettingNotFound(name); + BaseSettingsHelpers::throwSettingNotFound(name); } template diff --git a/src/Core/DecimalComparison.h b/src/Core/DecimalComparison.h index 63817e77805..77402adf164 100644 --- a/src/Core/DecimalComparison.h +++ b/src/Core/DecimalComparison.h @@ -109,7 +109,7 @@ private: { if (shift.left()) return apply(a, b, shift.a); - else if (shift.right()) + if (shift.right()) return apply(a, b, shift.b); return apply(a, b, 1); } diff --git a/src/Core/Joins.h b/src/Core/Joins.h index 96d2b51325c..0964bf86e6b 100644 --- a/src/Core/Joins.h +++ b/src/Core/Joins.h @@ -86,11 +86,11 @@ constexpr ASOFJoinInequality reverseASOFJoinInequality(ASOFJoinInequality inequa { if (inequality == ASOFJoinInequality::Less) return ASOFJoinInequality::Greater; - else if (inequality == ASOFJoinInequality::Greater) + if (inequality == ASOFJoinInequality::Greater) return ASOFJoinInequality::Less; - else if (inequality == ASOFJoinInequality::LessOrEquals) + if (inequality == ASOFJoinInequality::LessOrEquals) return ASOFJoinInequality::GreaterOrEquals; - else if (inequality == ASOFJoinInequality::GreaterOrEquals) + if (inequality == ASOFJoinInequality::GreaterOrEquals) return ASOFJoinInequality::LessOrEquals; return ASOFJoinInequality::None; diff --git a/src/Core/MySQL/IMySQLWritePacket.cpp b/src/Core/MySQL/IMySQLWritePacket.cpp index fd27603d6a8..5c5fea94925 100644 --- a/src/Core/MySQL/IMySQLWritePacket.cpp +++ b/src/Core/MySQL/IMySQLWritePacket.cpp @@ -30,18 +30,16 @@ size_t getLengthEncodedNumberSize(uint64_t x) { return 1; } - else if (x < (1 << 16)) + if (x < (1 << 16)) { return 3; } - else if (x < (1 << 24)) + if (x < (1 << 24)) { return 4; } - else - { - return 9; - } + + return 9; } size_t getLengthEncodedStringSize(const String & s) diff --git a/src/Core/MySQL/MySQLClient.cpp b/src/Core/MySQL/MySQLClient.cpp index 0a859e7259f..d5c7147b10a 100644 --- a/src/Core/MySQL/MySQLClient.cpp +++ b/src/Core/MySQL/MySQLClient.cpp @@ -96,7 +96,7 @@ void MySQLClient::handshake() if (packet_response.getType() == PACKET_ERR) throw Exception::createDeprecated(packet_response.err.error_message, ErrorCodes::UNKNOWN_PACKET_FROM_SERVER); - else if (packet_response.getType() == PACKET_AUTH_SWITCH) + if (packet_response.getType() == PACKET_AUTH_SWITCH) throw Exception(ErrorCodes::UNKNOWN_PACKET_FROM_SERVER, "Access denied for user {}", user); } diff --git a/src/Core/MySQL/MySQLReplication.cpp b/src/Core/MySQL/MySQLReplication.cpp index 6f18ce8978d..3e603d023c4 100644 --- a/src/Core/MySQL/MySQLReplication.cpp +++ b/src/Core/MySQL/MySQLReplication.cpp @@ -721,9 +721,9 @@ namespace MySQLReplication { if (precision <= DecimalUtils::max_precision) return Field(function(precision, scale, Decimal32())); - else if (precision <= DecimalUtils::max_precision) + if (precision <= DecimalUtils::max_precision) return Field(function(precision, scale, Decimal64())); - else if (precision <= DecimalUtils::max_precision) + if (precision <= DecimalUtils::max_precision) return Field(function(precision, scale, Decimal128())); return Field(function(precision, scale, Decimal256())); diff --git a/src/Core/PostgreSQL/insertPostgreSQLValue.cpp b/src/Core/PostgreSQL/insertPostgreSQLValue.cpp index 0ce7222a9a5..fa9871c6750 100644 --- a/src/Core/PostgreSQL/insertPostgreSQLValue.cpp +++ b/src/Core/PostgreSQL/insertPostgreSQLValue.cpp @@ -134,7 +134,7 @@ void insertPostgreSQLValue( if ((parsed.first == pqxx::array_parser::juncture::row_start) && (++dimension > expected_dimensions)) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Got more dimensions than expected"); - else if (parsed.first == pqxx::array_parser::juncture::string_value) + if (parsed.first == pqxx::array_parser::juncture::string_value) dimensions[dimension].emplace_back(parse_value(parsed.second)); else if (parsed.first == pqxx::array_parser::juncture::null_value) diff --git a/src/Core/QualifiedTableName.h b/src/Core/QualifiedTableName.h index 0fd72c32a54..5899c23ee91 100644 --- a/src/Core/QualifiedTableName.h +++ b/src/Core/QualifiedTableName.h @@ -44,16 +44,14 @@ struct QualifiedTableName { if (database.empty()) return {table}; - else - return {database, table}; + return {database, table}; } std::string getFullName() const { if (database.empty()) return table; - else - return database + '.' + table; + return database + '.' + table; } /// NOTE: It's different from compound identifier parsing and does not support escaping and dots in name. diff --git a/src/Core/SettingsFields.cpp b/src/Core/SettingsFields.cpp index bcfa6063cd5..ff055ec7a4f 100644 --- a/src/Core/SettingsFields.cpp +++ b/src/Core/SettingsFields.cpp @@ -55,25 +55,27 @@ namespace { return stringToNumber(f.safeGet()); } - else if (f.getType() == Field::Types::UInt64) + if (f.getType() == Field::Types::UInt64) { T result; if (!accurate::convertNumeric(f.safeGet(), result)) - throw Exception(ErrorCodes::CANNOT_CONVERT_TYPE, "Field value {} is out of range of {} type", f, demangle(typeid(T).name())); + throw Exception( + ErrorCodes::CANNOT_CONVERT_TYPE, "Field value {} is out of range of {} type", f, demangle(typeid(T).name())); return result; } - else if (f.getType() == Field::Types::Int64) + if (f.getType() == Field::Types::Int64) { T result; if (!accurate::convertNumeric(f.safeGet(), result)) - throw Exception(ErrorCodes::CANNOT_CONVERT_TYPE, "Field value {} is out of range of {} type", f, demangle(typeid(T).name())); + throw Exception( + ErrorCodes::CANNOT_CONVERT_TYPE, "Field value {} is out of range of {} type", f, demangle(typeid(T).name())); return result; } - else if (f.getType() == Field::Types::Bool) + if (f.getType() == Field::Types::Bool) { return T(f.safeGet()); } - else if (f.getType() == Field::Types::Float64) + if (f.getType() == Field::Types::Float64) { Float64 x = f.safeGet(); if constexpr (std::is_floating_point_v) @@ -87,16 +89,16 @@ namespace /// Conversion of infinite values to integer is undefined. throw Exception(ErrorCodes::CANNOT_CONVERT_TYPE, "Cannot convert infinite value to integer type"); } - else if (x > Float64(std::numeric_limits::max()) || x < Float64(std::numeric_limits::lowest())) + if (x > Float64(std::numeric_limits::max()) || x < Float64(std::numeric_limits::lowest())) { throw Exception(ErrorCodes::CANNOT_CONVERT_TYPE, "Cannot convert out of range floating point value to integer type"); } - else - return T(x); + return T(x); } } else - throw Exception(ErrorCodes::CANNOT_CONVERT_TYPE, "Invalid value {} of the setting, which needs {}", f, demangle(typeid(T).name())); + throw Exception( + ErrorCodes::CANNOT_CONVERT_TYPE, "Invalid value {} of the setting, which needs {}", f, demangle(typeid(T).name())); } Map stringToMap(const String & str) @@ -219,8 +221,7 @@ namespace { if (f.getType() == Field::Types::String) return stringToMaxThreads(f.safeGet()); - else - return fieldToNumber(f); + return fieldToNumber(f); } } @@ -239,8 +240,7 @@ String SettingFieldMaxThreads::toString() const if (is_auto) /// Removing quotes here will introduce an incompatibility between replicas with different versions. return "'auto(" + ::DB::toString(value) + ")'"; - else - return ::DB::toString(value); + return ::DB::toString(value); } void SettingFieldMaxThreads::parseFromString(const String & str) diff --git a/src/Core/SortCursor.h b/src/Core/SortCursor.h index 56e50d3a94f..f41664a1607 100644 --- a/src/Core/SortCursor.h +++ b/src/Core/SortCursor.h @@ -600,7 +600,7 @@ public: initializeQueues(); return; } - else if (sort_description.size() == 1) + if (sort_description.size() == 1) { TypeIndex column_type_index = sort_description_types[0]->getTypeId(); @@ -723,7 +723,7 @@ bool less(const TLeftColumns & lhs, const TRightColumns & rhs, size_t i, size_t int res = elem.base.direction * lhs[ind]->compareAt(i, j, *rhs[ind], elem.base.nulls_direction); if (res < 0) return true; - else if (res > 0) + if (res > 0) return false; } diff --git a/src/Daemon/BaseDaemon.cpp b/src/Daemon/BaseDaemon.cpp index c9ccbb26d3a..8a8dd3c759c 100644 --- a/src/Daemon/BaseDaemon.cpp +++ b/src/Daemon/BaseDaemon.cpp @@ -797,11 +797,9 @@ void systemdNotify(const std::string_view & command) { if (errno == EINTR) continue; - else - throw ErrnoException(ErrorCodes::SYSTEM_ERROR, "Failed to notify systemd, sendto returned error"); + throw ErrnoException(ErrorCodes::SYSTEM_ERROR, "Failed to notify systemd, sendto returned error"); } - else - sent_bytes_total += sent_bytes; + sent_bytes_total += sent_bytes; } } #endif diff --git a/src/Daemon/BaseDaemon.h b/src/Daemon/BaseDaemon.h index a6efa94a567..11aea1ecb67 100644 --- a/src/Daemon/BaseDaemon.h +++ b/src/Daemon/BaseDaemon.h @@ -187,8 +187,7 @@ std::optional> BaseDaemon::tryGetInstance() if (ptr) return std::optional>(*ptr); - else - return {}; + return {}; } #if defined(OS_LINUX) diff --git a/src/DataTypes/DataTypeDecimalBase.h b/src/DataTypes/DataTypeDecimalBase.h index 997c554059b..c1e1d27557f 100644 --- a/src/DataTypes/DataTypeDecimalBase.h +++ b/src/DataTypes/DataTypeDecimalBase.h @@ -200,10 +200,10 @@ inline DataTypePtr createDecimal(UInt64 precision_value, UInt64 scale_value) if (precision_value <= DecimalUtils::max_precision) return std::make_shared>(precision_value, scale_value); - else if (precision_value <= DecimalUtils::max_precision) + if (precision_value <= DecimalUtils::max_precision) return std::make_shared>(precision_value, scale_value); - else if (precision_value <= DecimalUtils::max_precision) - return std::make_shared>(precision_value, scale_value); + if (precision_value <= DecimalUtils::max_precision) + return std::make_shared>(precision_value, scale_value); return std::make_shared>(precision_value, scale_value); } diff --git a/src/DataTypes/DataTypeEnum.cpp b/src/DataTypes/DataTypeEnum.cpp index b9a5a1a5a68..7c208b23818 100644 --- a/src/DataTypes/DataTypeEnum.cpp +++ b/src/DataTypes/DataTypeEnum.cpp @@ -125,15 +125,13 @@ Field DataTypeEnum::castToName(const Field & value_or_name) const this->getValue(value_or_name.safeGet()); /// Check correctness return value_or_name.safeGet(); } - else if (value_or_name.getType() == Field::Types::Int64) + if (value_or_name.getType() == Field::Types::Int64) { Int64 value = value_or_name.safeGet(); checkOverflow(value); return this->getNameForValue(static_cast(value)).toString(); } - else - throw Exception(ErrorCodes::BAD_TYPE_OF_FIELD, - "DataTypeEnum: Unsupported type of field {}", value_or_name.getTypeName()); + throw Exception(ErrorCodes::BAD_TYPE_OF_FIELD, "DataTypeEnum: Unsupported type of field {}", value_or_name.getTypeName()); } template @@ -143,17 +141,14 @@ Field DataTypeEnum::castToValue(const Field & value_or_name) const { return this->getValue(value_or_name.safeGet()); } - else if (value_or_name.getType() == Field::Types::Int64 - || value_or_name.getType() == Field::Types::UInt64) + if (value_or_name.getType() == Field::Types::Int64 || value_or_name.getType() == Field::Types::UInt64) { Int64 value = value_or_name.safeGet(); checkOverflow(value); this->getNameForValue(static_cast(value)); /// Check correctness return value; } - else - throw Exception(ErrorCodes::BAD_TYPE_OF_FIELD, - "DataTypeEnum: Unsupported type of field {}", value_or_name.getTypeName()); + throw Exception(ErrorCodes::BAD_TYPE_OF_FIELD, "DataTypeEnum: Unsupported type of field {}", value_or_name.getTypeName()); } diff --git a/src/DataTypes/DataTypeFactory.cpp b/src/DataTypes/DataTypeFactory.cpp index cff9a2e4591..24334000d6c 100644 --- a/src/DataTypes/DataTypeFactory.cpp +++ b/src/DataTypes/DataTypeFactory.cpp @@ -249,8 +249,7 @@ const DataTypeFactory::Value * DataTypeFactory::findCreatorByName(const String & auto hints = this->getHints(family_name); if (!hints.empty()) throw Exception(ErrorCodes::UNKNOWN_TYPE, "Unknown data type family: {}. Maybe you meant: {}", family_name, toString(hints)); - else - throw Exception(ErrorCodes::UNKNOWN_TYPE, "Unknown data type family: {}", family_name); + throw Exception(ErrorCodes::UNKNOWN_TYPE, "Unknown data type family: {}", family_name); } DataTypeFactory::DataTypeFactory() diff --git a/src/DataTypes/DataTypeLowCardinality.cpp b/src/DataTypes/DataTypeLowCardinality.cpp index 5af1f28cbad..39b51921239 100644 --- a/src/DataTypes/DataTypeLowCardinality.cpp +++ b/src/DataTypes/DataTypeLowCardinality.cpp @@ -75,23 +75,23 @@ MutableColumnUniquePtr DataTypeLowCardinality::createColumnUniqueImpl(const IDat if (which.isString()) return creator(static_cast(nullptr)); - else if (which.isFixedString()) + if (which.isFixedString()) return creator(static_cast(nullptr)); - else if (which.isDate()) + if (which.isDate()) return creator(static_cast *>(nullptr)); - else if (which.isDate32()) + if (which.isDate32()) return creator(static_cast *>(nullptr)); - else if (which.isDateTime()) + if (which.isDateTime()) return creator(static_cast *>(nullptr)); - else if (which.isUUID()) + if (which.isUUID()) return creator(static_cast *>(nullptr)); - else if (which.isIPv4()) + if (which.isIPv4()) return creator(static_cast *>(nullptr)); - else if (which.isIPv6()) + if (which.isIPv6()) return creator(static_cast *>(nullptr)); - else if (which.isInterval()) + if (which.isInterval()) return creator(static_cast(nullptr)); - else if (which.isInt() || which.isUInt() || which.isFloat()) + if (which.isInt() || which.isUInt() || which.isFloat()) { MutableColumnUniquePtr column; TypeListUtils::forEach(TypeListIntAndFloat{}, CreateColumnVector(column, *type, creator)); diff --git a/src/DataTypes/DataTypeLowCardinalityHelpers.cpp b/src/DataTypes/DataTypeLowCardinalityHelpers.cpp index e2b2831db51..a2a70a8b706 100644 --- a/src/DataTypes/DataTypeLowCardinalityHelpers.cpp +++ b/src/DataTypes/DataTypeLowCardinalityHelpers.cpp @@ -39,8 +39,7 @@ DataTypePtr recursiveRemoveLowCardinality(const DataTypePtr & type) if (tuple_type->haveExplicitNames()) return std::make_shared(elements, tuple_type->getElementNames()); - else - return std::make_shared(elements); + return std::make_shared(elements); } if (const auto * map_type = typeid_cast(type.get())) diff --git a/src/DataTypes/DataTypeTuple.cpp b/src/DataTypes/DataTypeTuple.cpp index 75556ed4090..bceb0f844c8 100644 --- a/src/DataTypes/DataTypeTuple.cpp +++ b/src/DataTypes/DataTypeTuple.cpp @@ -415,10 +415,9 @@ static DataTypePtr create(const ASTPtr & arguments) if (names.empty()) return std::make_shared(nested_types); - else if (names.size() != nested_types.size()) + if (names.size() != nested_types.size()) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Names are specified not for all elements of Tuple type"); - else - return std::make_shared(nested_types, names); + return std::make_shared(nested_types, names); } diff --git a/src/DataTypes/DataTypesDecimal.cpp b/src/DataTypes/DataTypesDecimal.cpp index 1d8f7711de1..038a00932ee 100644 --- a/src/DataTypes/DataTypesDecimal.cpp +++ b/src/DataTypes/DataTypesDecimal.cpp @@ -41,8 +41,7 @@ DataTypePtr DataTypeDecimal::promoteNumericType() const { if (sizeof(T) <= sizeof(Decimal128)) return std::make_shared>(DataTypeDecimal::maxPrecision(), this->scale); - else - return std::make_shared>(DataTypeDecimal::maxPrecision(), this->scale); + return std::make_shared>(DataTypeDecimal::maxPrecision(), this->scale); } template diff --git a/src/DataTypes/EnumValues.cpp b/src/DataTypes/EnumValues.cpp index 8320044487e..8e9470cf13f 100644 --- a/src/DataTypes/EnumValues.cpp +++ b/src/DataTypes/EnumValues.cpp @@ -61,17 +61,15 @@ T EnumValues::getValue(StringRef field_name) const { return it->getMapped(); } - else if (tryParse(x, field_name.data, field_name.size) && value_to_name_map.contains(x)) + if (tryParse(x, field_name.data, field_name.size) && value_to_name_map.contains(x)) { /// If we fail to find given string in enum names, we will try to treat it as enum id. return x; } - else - { - auto hints = this->getHints(field_name.toString()); - auto hints_string = !hints.empty() ? ", maybe you meant: " + toString(hints) : ""; - throw Exception(ErrorCodes::UNKNOWN_ELEMENT_OF_ENUM, "Unknown element '{}' for enum{}", field_name.toString(), hints_string); - } + + auto hints = this->getHints(field_name.toString()); + auto hints_string = !hints.empty() ? ", maybe you meant: " + toString(hints) : ""; + throw Exception(ErrorCodes::UNKNOWN_ELEMENT_OF_ENUM, "Unknown element '{}' for enum{}", field_name.toString(), hints_string); } template @@ -82,11 +80,9 @@ bool EnumValues::tryGetValue(T & x, StringRef field_name) const x = it->getMapped(); return true; } - else - { - /// If we fail to find given string in enum names, we will try to treat it as enum id. - return tryParse(x, field_name.data, field_name.size) && value_to_name_map.contains(x); - } + + /// If we fail to find given string in enum names, we will try to treat it as enum id. + return tryParse(x, field_name.data, field_name.size) && value_to_name_map.contains(x); } template diff --git a/src/DataTypes/IDataType.h b/src/DataTypes/IDataType.h index a7665e610ab..b9b0029fd94 100644 --- a/src/DataTypes/IDataType.h +++ b/src/DataTypes/IDataType.h @@ -76,16 +76,14 @@ public: { if (custom_name) return custom_name->getName(); - else - return doGetName(); + return doGetName(); } String getPrettyName(size_t indent = 0) const { if (custom_name) return custom_name->getName(); - else - return doGetPrettyName(indent); + return doGetPrettyName(indent); } DataTypePtr getPtr() const { return shared_from_this(); } diff --git a/src/DataTypes/Native.cpp b/src/DataTypes/Native.cpp index fd3716c2291..5dc490b0bd5 100644 --- a/src/DataTypes/Native.cpp +++ b/src/DataTypes/Native.cpp @@ -60,19 +60,19 @@ llvm::Type * toNativeType(llvm::IRBuilderBase & builder, const IDataType & type) /// LLVM doesn't have unsigned types, it has unsigned instructions. if (data_type.isInt8() || data_type.isUInt8()) return builder.getInt8Ty(); - else if (data_type.isInt16() || data_type.isUInt16() || data_type.isDate()) + if (data_type.isInt16() || data_type.isUInt16() || data_type.isDate()) return builder.getInt16Ty(); - else if (data_type.isInt32() || data_type.isUInt32() || data_type.isDate32() || data_type.isDateTime()) + if (data_type.isInt32() || data_type.isUInt32() || data_type.isDate32() || data_type.isDateTime()) return builder.getInt32Ty(); - else if (data_type.isInt64() || data_type.isUInt64()) + if (data_type.isInt64() || data_type.isUInt64()) return builder.getInt64Ty(); - else if (data_type.isFloat32()) + if (data_type.isFloat32()) return builder.getFloatTy(); - else if (data_type.isFloat64()) + if (data_type.isFloat64()) return builder.getDoubleTy(); - else if (data_type.isEnum8()) + if (data_type.isEnum8()) return builder.getInt8Ty(); - else if (data_type.isEnum16()) + if (data_type.isEnum16()) return builder.getInt16Ty(); throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid cast to native type"); @@ -95,7 +95,7 @@ llvm::Value * nativeBoolCast(llvm::IRBuilderBase & b, const DataTypePtr & from_t if (value->getType()->isIntegerTy()) return b.CreateICmpNE(value, zero); - else if (value->getType()->isFloatingPointTy()) + if (value->getType()->isFloatingPointTy()) return b.CreateFCmpUNE(value, zero); throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Cannot cast non-number {} to bool", from_type->getName()); @@ -112,37 +112,34 @@ llvm::Value * nativeCast(llvm::IRBuilderBase & b, const DataTypePtr & from_type, { return value; } - else if (from_type->isNullable() && to_type->isNullable()) + if (from_type->isNullable() && to_type->isNullable()) { auto * inner = nativeCast(b, removeNullable(from_type), b.CreateExtractValue(value, {0}), to_type); return b.CreateInsertValue(inner, b.CreateExtractValue(value, {1}), {1}); } - else if (from_type->isNullable()) + if (from_type->isNullable()) { return nativeCast(b, removeNullable(from_type), b.CreateExtractValue(value, {0}), to_type); } - else if (to_type->isNullable()) + if (to_type->isNullable()) { auto * to_native_type = toNativeType(b, to_type); auto * inner = nativeCast(b, from_type, value, removeNullable(to_type)); return b.CreateInsertValue(llvm::Constant::getNullValue(to_native_type), inner, {0}); } - else - { - auto * from_native_type = toNativeType(b, from_type); - auto * to_native_type = toNativeType(b, to_type); + auto * from_native_type = toNativeType(b, from_type); + auto * to_native_type = toNativeType(b, to_type); - if (from_native_type == to_native_type) - return value; - else if (from_native_type->isIntegerTy() && to_native_type->isFloatingPointTy()) - return typeIsSigned(*from_type) ? b.CreateSIToFP(value, to_native_type) : b.CreateUIToFP(value, to_native_type); - else if (from_native_type->isFloatingPointTy() && to_native_type->isIntegerTy()) - return typeIsSigned(*to_type) ? b.CreateFPToSI(value, to_native_type) : b.CreateFPToUI(value, to_native_type); - else if (from_native_type->isIntegerTy() && from_native_type->isIntegerTy()) - return b.CreateIntCast(value, to_native_type, typeIsSigned(*from_type)); - else if (to_native_type->isFloatingPointTy() && to_native_type->isFloatingPointTy()) - return b.CreateFPCast(value, to_native_type); - } + if (from_native_type == to_native_type) + return value; + if (from_native_type->isIntegerTy() && to_native_type->isFloatingPointTy()) + return typeIsSigned(*from_type) ? b.CreateSIToFP(value, to_native_type) : b.CreateUIToFP(value, to_native_type); + if (from_native_type->isFloatingPointTy() && to_native_type->isIntegerTy()) + return typeIsSigned(*to_type) ? b.CreateFPToSI(value, to_native_type) : b.CreateFPToUI(value, to_native_type); + if (from_native_type->isIntegerTy() && from_native_type->isIntegerTy()) + return b.CreateIntCast(value, to_native_type, typeIsSigned(*from_type)); + if (to_native_type->isFloatingPointTy() && to_native_type->isFloatingPointTy()) + return b.CreateFPCast(value, to_native_type); throw Exception(ErrorCodes::LOGICAL_ERROR, "Invalid cast to native value from type {} to type {}", @@ -173,19 +170,19 @@ llvm::Constant * getColumnNativeValue(llvm::IRBuilderBase & builder, const DataT return llvm::ConstantStruct::get(static_cast(type), value, is_null); } - else if (column_data_type.isFloat32()) + if (column_data_type.isFloat32()) { return llvm::ConstantFP::get(type, assert_cast &>(column).getElement(index)); } - else if (column_data_type.isFloat64()) + if (column_data_type.isFloat64()) { return llvm::ConstantFP::get(type, assert_cast &>(column).getElement(index)); } - else if (column_data_type.isNativeUInt() || column_data_type.isDate() || column_data_type.isDateTime()) + if (column_data_type.isNativeUInt() || column_data_type.isDate() || column_data_type.isDateTime()) { return llvm::ConstantInt::get(type, column.getUInt(index)); } - else if (column_data_type.isNativeInt() || column_data_type.isEnum() || column_data_type.isDate32()) + if (column_data_type.isNativeInt() || column_data_type.isEnum() || column_data_type.isDate32()) { return llvm::ConstantInt::get(type, column.getInt(index)); } diff --git a/src/DataTypes/NestedUtils.cpp b/src/DataTypes/NestedUtils.cpp index 650559d21d9..d294e9fa121 100644 --- a/src/DataTypes/NestedUtils.cpp +++ b/src/DataTypes/NestedUtils.cpp @@ -352,10 +352,8 @@ std::optional NestedColumnExtractHelper::extractColumn( column.name = original_column_name; return {std::move(column)}; } - else - { - return {}; - } + + return {}; } if (!nested_table->has(new_column_name_prefix, case_insentive)) diff --git a/src/DataTypes/ObjectUtils.cpp b/src/DataTypes/ObjectUtils.cpp index fb64199a1b0..4f3c22aa8a3 100644 --- a/src/DataTypes/ObjectUtils.cpp +++ b/src/DataTypes/ObjectUtils.cpp @@ -313,7 +313,7 @@ static bool hasDifferentStructureInPrefix(const PathInData::Parts & lhs, const P { if (lhs[i].key != rhs[i].key) return false; - else if (lhs[i] != rhs[i]) + if (lhs[i] != rhs[i]) return true; } return false; @@ -715,7 +715,7 @@ ColumnWithTypeAndDimensions createTypeFromNode(const Node & node) { return node.data; } - else if (node.kind == Node::NESTED) + if (node.kind == Node::NESTED) { auto [tuple_names, tuple_columns] = collect_tuple_elemets(node.children); @@ -782,26 +782,24 @@ ColumnWithTypeAndDimensions createTypeFromNode(const Node & node) return {result_column, result_type, tuple_columns[0].array_dimensions}; } - else + + auto [tuple_names, tuple_columns] = collect_tuple_elemets(node.children); + + size_t num_elements = tuple_columns.size(); + Columns tuple_elements_columns(num_elements); + DataTypes tuple_elements_types(num_elements); + + for (size_t i = 0; i < tuple_columns.size(); ++i) { - auto [tuple_names, tuple_columns] = collect_tuple_elemets(node.children); - - size_t num_elements = tuple_columns.size(); - Columns tuple_elements_columns(num_elements); - DataTypes tuple_elements_types(num_elements); - - for (size_t i = 0; i < tuple_columns.size(); ++i) - { - assert(tuple_columns[i].array_dimensions == tuple_columns[0].array_dimensions); - tuple_elements_columns[i] = tuple_columns[i].column; - tuple_elements_types[i] = tuple_columns[i].type; - } - - auto result_column = ColumnTuple::create(tuple_elements_columns); - auto result_type = std::make_shared(tuple_elements_types, tuple_names); - - return {result_column, result_type, tuple_columns[0].array_dimensions}; + assert(tuple_columns[i].array_dimensions == tuple_columns[0].array_dimensions); + tuple_elements_columns[i] = tuple_columns[i].column; + tuple_elements_types[i] = tuple_columns[i].type; } + + auto result_column = ColumnTuple::create(tuple_elements_columns); + auto result_type = std::make_shared(tuple_elements_types, tuple_names); + + return {result_column, result_type, tuple_columns[0].array_dimensions}; } } diff --git a/src/DataTypes/Serializations/ISerialization.cpp b/src/DataTypes/Serializations/ISerialization.cpp index dcf637c7d2b..fdcdf9e0cda 100644 --- a/src/DataTypes/Serializations/ISerialization.cpp +++ b/src/DataTypes/Serializations/ISerialization.cpp @@ -42,10 +42,9 @@ ISerialization::Kind ISerialization::stringToKind(const String & str) { if (str == "Default") return Kind::DEFAULT; - else if (str == "Sparse") + if (str == "Sparse") return Kind::SPARSE; - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown serialization kind '{}'", str); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown serialization kind '{}'", str); } const std::set ISerialization::Substream::named_types diff --git a/src/DataTypes/Serializations/SerializationArray.cpp b/src/DataTypes/Serializations/SerializationArray.cpp index 5562bc58494..b7c002c95fc 100644 --- a/src/DataTypes/Serializations/SerializationArray.cpp +++ b/src/DataTypes/Serializations/SerializationArray.cpp @@ -642,12 +642,11 @@ ReturnType SerializationArray::deserializeTextJSONImpl(IColumn & column, ReadBuf { return JSONUtils::deserializeEmpyStringAsDefaultOrNested(nested_column, istr, deserialize_nested); }, false); - else - return deserializeTextImpl(column, istr, - [&deserialize_nested, &istr](IColumn & nested_column) -> ReturnType - { - return deserialize_nested(nested_column, istr); - }, false); + return deserializeTextImpl( + column, + istr, + [&deserialize_nested, &istr](IColumn & nested_column) -> ReturnType { return deserialize_nested(nested_column, istr); }, + false); } @@ -740,17 +739,15 @@ bool SerializationArray::tryDeserializeTextCSV(IColumn & column, ReadBuffer & is return deserializeTextImpl(column, rb, read_nested, true); } - else + + auto read_nested = [&](IColumn & nested_column) { - auto read_nested = [&](IColumn & nested_column) - { - if (settings.null_as_default && !isColumnNullableOrLowCardinalityNullable(nested_column)) - return SerializationNullable::tryDeserializeNullAsDefaultOrNestedTextQuoted(nested_column, rb, settings, nested); - return nested->tryDeserializeTextQuoted(nested_column, rb, settings); - }; + if (settings.null_as_default && !isColumnNullableOrLowCardinalityNullable(nested_column)) + return SerializationNullable::tryDeserializeNullAsDefaultOrNestedTextQuoted(nested_column, rb, settings, nested); + return nested->tryDeserializeTextQuoted(nested_column, rb, settings); + }; - return deserializeTextImpl(column, rb, read_nested, true); - } + return deserializeTextImpl(column, rb, read_nested, true); } } diff --git a/src/DataTypes/Serializations/SerializationDynamic.cpp b/src/DataTypes/Serializations/SerializationDynamic.cpp index 18a75918499..109f14d49f0 100644 --- a/src/DataTypes/Serializations/SerializationDynamic.cpp +++ b/src/DataTypes/Serializations/SerializationDynamic.cpp @@ -481,7 +481,7 @@ void SerializationDynamic::serializeBinary(const IColumn & column, size_t row_nu } /// Check if this value is in shared variant. In this case it's already /// in desired binary format. - else if (global_discr == dynamic_column.getSharedVariantDiscriminator()) + if (global_discr == dynamic_column.getSharedVariantDiscriminator()) { auto value = dynamic_column.getSharedVariant().getDataAt(variant_column.offsetAt(row_num)); ostr.write(value.data, value.size); diff --git a/src/DataTypes/Serializations/SerializationInfo.cpp b/src/DataTypes/Serializations/SerializationInfo.cpp index df9d27d4ca2..172a71204f9 100644 --- a/src/DataTypes/Serializations/SerializationInfo.cpp +++ b/src/DataTypes/Serializations/SerializationInfo.cpp @@ -317,7 +317,7 @@ SerializationInfoByName SerializationInfoByName::readJSON( auto array = object->getArray(KEY_COLUMNS); for (const auto & elem : *array) { - auto elem_object = elem.extract(); + const auto & elem_object = elem.extract(); if (!elem_object->has(KEY_NAME)) throw Exception(ErrorCodes::CORRUPTED_DATA, diff --git a/src/DataTypes/Serializations/SerializationLowCardinality.cpp b/src/DataTypes/Serializations/SerializationLowCardinality.cpp index 3195a04d348..baaab6ba3c3 100644 --- a/src/DataTypes/Serializations/SerializationLowCardinality.cpp +++ b/src/DataTypes/Serializations/SerializationLowCardinality.cpp @@ -411,15 +411,13 @@ namespace { if (auto * data_uint8 = getIndexesData(column)) return mapIndexWithAdditionalKeys(*data_uint8, dict_size); - else if (auto * data_uint16 = getIndexesData(column)) + if (auto * data_uint16 = getIndexesData(column)) return mapIndexWithAdditionalKeys(*data_uint16, dict_size); - else if (auto * data_uint32 = getIndexesData(column)) + if (auto * data_uint32 = getIndexesData(column)) return mapIndexWithAdditionalKeys(*data_uint32, dict_size); - else if (auto * data_uint64 = getIndexesData(column)) + if (auto * data_uint64 = getIndexesData(column)) return mapIndexWithAdditionalKeys(*data_uint64, dict_size); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Indexes column for mapIndexWithAdditionalKeys must be UInt, got {}", - column.getName()); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Indexes column for mapIndexWithAdditionalKeys must be UInt, got {}", column.getName()); } } diff --git a/src/DataTypes/Serializations/SerializationMap.cpp b/src/DataTypes/Serializations/SerializationMap.cpp index ae864cbf7b4..6538589e4f8 100644 --- a/src/DataTypes/Serializations/SerializationMap.cpp +++ b/src/DataTypes/Serializations/SerializationMap.cpp @@ -347,12 +347,11 @@ ReturnType SerializationMap::deserializeTextJSONImpl(IColumn & column, ReadBuffe return deserialize_nested(subcolumn_, buf_, subcolumn_serialization); }); }); - else - return deserializeTextImpl(column, istr, - [&deserialize_nested](ReadBuffer & buf, const SerializationPtr & subcolumn_serialization, IColumn & subcolumn) -> ReturnType - { - return deserialize_nested(subcolumn, buf, subcolumn_serialization); - }); + return deserializeTextImpl( + column, + istr, + [&deserialize_nested](ReadBuffer & buf, const SerializationPtr & subcolumn_serialization, IColumn & subcolumn) -> ReturnType + { return deserialize_nested(subcolumn, buf, subcolumn_serialization); }); } void SerializationMap::deserializeTextJSON(IColumn & column, ReadBuffer & istr, const FormatSettings & settings) const diff --git a/src/DataTypes/Serializations/SerializationTuple.cpp b/src/DataTypes/Serializations/SerializationTuple.cpp index e1fcb1a8d48..366949e7ac0 100644 --- a/src/DataTypes/Serializations/SerializationTuple.cpp +++ b/src/DataTypes/Serializations/SerializationTuple.cpp @@ -92,10 +92,9 @@ static ReturnType addElementSafe(size_t num_elems, IColumn & column, F && impl) restore_elements(); return ReturnType(false); } - else - { - assert_cast(column).addSize(1); - } + + assert_cast(column).addSize(1); + // Check that all columns now have the same size. size_t new_size = column.size(); @@ -378,12 +377,14 @@ ReturnType SerializationTuple::deserializeTupleJSONImpl(IColumn & column, ReadBu ++skipped; continue; } - else - { - if constexpr (throw_exception) - throw Exception(ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK, "Tuple doesn't have element with name '{}', enable setting input_format_json_ignore_unknown_keys_in_named_tuple", name); - return false; - } + + if constexpr (throw_exception) + throw Exception( + ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK, + "Tuple doesn't have element with name '{}', enable setting " + "input_format_json_ignore_unknown_keys_in_named_tuple", + name); + return false; } seen_elements[element_pos] = 1; @@ -445,48 +446,46 @@ ReturnType SerializationTuple::deserializeTupleJSONImpl(IColumn & column, ReadBu return addElementSafe(elems.size(), column, impl); } - else + + skipWhitespaceIfAny(istr); + if constexpr (throw_exception) + assertChar('[', istr); + else if (!checkChar('[', istr)) + return false; + skipWhitespaceIfAny(istr); + + auto impl = [&]() { - skipWhitespaceIfAny(istr); - if constexpr (throw_exception) - assertChar('[', istr); - else if (!checkChar('[', istr)) - return false; - skipWhitespaceIfAny(istr); - - auto impl = [&]() + for (size_t i = 0; i < elems.size(); ++i) { - for (size_t i = 0; i < elems.size(); ++i) + skipWhitespaceIfAny(istr); + if (i != 0) { - skipWhitespaceIfAny(istr); - if (i != 0) - { - if constexpr (throw_exception) - assertChar(',', istr); - else if (!checkChar(',', istr)) - return false; - skipWhitespaceIfAny(istr); - } - - auto & element_column = extractElementColumn(column, i); - if constexpr (throw_exception) - deserialize_element(element_column, i); - else if (!deserialize_element(element_column, i)) + assertChar(',', istr); + else if (!checkChar(',', istr)) return false; + skipWhitespaceIfAny(istr); } - skipWhitespaceIfAny(istr); + auto & element_column = extractElementColumn(column, i); + if constexpr (throw_exception) - assertChar(']', istr); - else if (!checkChar(']', istr)) + deserialize_element(element_column, i); + else if (!deserialize_element(element_column, i)) return false; + } - return true; - }; + skipWhitespaceIfAny(istr); + if constexpr (throw_exception) + assertChar(']', istr); + else if (!checkChar(']', istr)) + return false; - return addElementSafe(elems.size(), column, impl); - } + return true; + }; + + return addElementSafe(elems.size(), column, impl); } template @@ -505,8 +504,7 @@ ReturnType SerializationTuple::deserializeTextJSONImpl(IColumn & column, ReadBuf { if (settings.null_as_default && !isColumnNullableOrLowCardinalityNullable(nested_column)) return SerializationNullable::tryDeserializeNullAsDefaultOrNestedTextJSON(nested_column, buf, settings, nested_column_serialization); - else - return nested_column_serialization->tryDeserializeTextJSON(nested_column, buf, settings); + return nested_column_serialization->tryDeserializeTextJSON(nested_column, buf, settings); } }; @@ -520,12 +518,12 @@ ReturnType SerializationTuple::deserializeTextJSONImpl(IColumn & column, ReadBuf return deserialize_nested(nested_column_, buf, elems[element_pos]); }); }); - else - return deserializeTupleJSONImpl(column, istr, settings, - [&deserialize_nested, &istr, this](IColumn & nested_column, size_t element_pos) -> ReturnType - { - return deserialize_nested(nested_column, istr, elems[element_pos]); - }); + return deserializeTupleJSONImpl( + column, + istr, + settings, + [&deserialize_nested, &istr, this](IColumn & nested_column, size_t element_pos) -> ReturnType + { return deserialize_nested(nested_column, istr, elems[element_pos]); }); } void SerializationTuple::deserializeTextJSON(IColumn & column, ReadBuffer & istr, const FormatSettings & settings) const @@ -637,14 +635,12 @@ bool SerializationTuple::tryDeserializeTextCSV(IColumn & column, ReadBuffer & is return true; }); } - else - { - String s; - if (!tryReadCSV(s, istr, settings.csv)) - return false; - ReadBufferFromString rb(s); - return tryDeserializeText(column, rb, settings, true); - } + + String s; + if (!tryReadCSV(s, istr, settings.csv)) + return false; + ReadBufferFromString rb(s); + return tryDeserializeText(column, rb, settings, true); } struct SerializeBinaryBulkStateTuple : public ISerialization::SerializeBinaryBulkState diff --git a/src/DataTypes/Serializations/SerializationVariant.cpp b/src/DataTypes/Serializations/SerializationVariant.cpp index 0f6a17ef167..a05e977bfe2 100644 --- a/src/DataTypes/Serializations/SerializationVariant.cpp +++ b/src/DataTypes/Serializations/SerializationVariant.cpp @@ -272,7 +272,7 @@ void SerializationVariant::serializeBinaryBulkWithMultipleStreamsAndUpdateVarian return; } /// If column has only NULLs, just serialize NULL discriminators. - else if (col.hasOnlyNulls()) + if (col.hasOnlyNulls()) { /// In compact mode write single NULL_DISCRIMINATOR. if (variant_state->discriminators_mode.value == DiscriminatorsSerializationMode::COMPACT) @@ -859,7 +859,7 @@ bool SerializationVariant::tryDeserializeImpl( column_variant.getOffsets().push_back(prev_size); return true; } - else if (variant_column.size() > prev_size) + if (variant_column.size() > prev_size) { variant_column.popBack(1); } diff --git a/src/DataTypes/getLeastSupertype.cpp b/src/DataTypes/getLeastSupertype.cpp index 65df529e78b..9664e769611 100644 --- a/src/DataTypes/getLeastSupertype.cpp +++ b/src/DataTypes/getLeastSupertype.cpp @@ -147,12 +147,13 @@ DataTypePtr getNumericType(const TypeIndexSet & types) size_t min_mantissa_bits = std::max(min_bit_width_of_integer, max_mantissa_bits_of_floating); if (min_mantissa_bits <= 24) return std::make_shared(); - else if (min_mantissa_bits <= 53) + if (min_mantissa_bits <= 53) return std::make_shared(); - else - return throwOrReturn(types, - " because some of them are integers and some are floating point," - " but there is no floating point type, that can exactly represent all required integers", ErrorCodes::NO_COMMON_TYPE); + return throwOrReturn( + types, + " because some of them are integers and some are floating point," + " but there is no floating point type, that can exactly represent all required integers", + ErrorCodes::NO_COMMON_TYPE); } /// If the result must be signed integer. @@ -160,39 +161,41 @@ DataTypePtr getNumericType(const TypeIndexSet & types) { if (min_bit_width_of_integer <= 8) return std::make_shared(); - else if (min_bit_width_of_integer <= 16) + if (min_bit_width_of_integer <= 16) return std::make_shared(); - else if (min_bit_width_of_integer <= 32) + if (min_bit_width_of_integer <= 32) return std::make_shared(); - else if (min_bit_width_of_integer <= 64) + if (min_bit_width_of_integer <= 64) return std::make_shared(); - else if (min_bit_width_of_integer <= 128) + if (min_bit_width_of_integer <= 128) return std::make_shared(); - else if (min_bit_width_of_integer <= 256) + if (min_bit_width_of_integer <= 256) return std::make_shared(); - else - return throwOrReturn(types, - " because some of them are signed integers and some are unsigned integers," - " but there is no signed integer type, that can exactly represent all required unsigned integer values", ErrorCodes::NO_COMMON_TYPE); + return throwOrReturn( + types, + " because some of them are signed integers and some are unsigned integers," + " but there is no signed integer type, that can exactly represent all required unsigned integer values", + ErrorCodes::NO_COMMON_TYPE); } /// All unsigned. { if (min_bit_width_of_integer <= 8) return std::make_shared(); - else if (min_bit_width_of_integer <= 16) + if (min_bit_width_of_integer <= 16) return std::make_shared(); - else if (min_bit_width_of_integer <= 32) + if (min_bit_width_of_integer <= 32) return std::make_shared(); - else if (min_bit_width_of_integer <= 64) + if (min_bit_width_of_integer <= 64) return std::make_shared(); - else if (min_bit_width_of_integer <= 128) + if (min_bit_width_of_integer <= 128) return std::make_shared(); - else if (min_bit_width_of_integer <= 256) + if (min_bit_width_of_integer <= 256) return std::make_shared(); - else - return throwOrReturn(types, - " but as all data types are unsigned integers, we must have found maximum unsigned integer type", ErrorCodes::NO_COMMON_TYPE); + return throwOrReturn( + types, + " but as all data types are unsigned integers, we must have found maximum unsigned integer type", + ErrorCodes::NO_COMMON_TYPE); } } @@ -474,16 +477,14 @@ DataTypePtr getLeastSupertype(const DataTypes & types) { if (have_not_low_cardinality) return getLeastSupertype(nested_types); - else - { - auto nested_type = getLeastSupertype(nested_types); - /// When on_error == LeastSupertypeOnError::Null and we cannot get least supertype, - /// nested_type will be nullptr, we should return nullptr in this case. - if (!nested_type) - return nullptr; - return std::make_shared(nested_type); - } + auto nested_type = getLeastSupertype(nested_types); + + /// When on_error == LeastSupertypeOnError::Null and we cannot get least supertype, + /// nested_type will be nullptr, we should return nullptr in this case. + if (!nested_type) + return nullptr; + return std::make_shared(nested_type); } } diff --git a/src/DataTypes/getMostSubtype.cpp b/src/DataTypes/getMostSubtype.cpp index 33b5735456e..b3c76079646 100644 --- a/src/DataTypes/getMostSubtype.cpp +++ b/src/DataTypes/getMostSubtype.cpp @@ -315,12 +315,13 @@ DataTypePtr getMostSubtype(const DataTypes & types, bool throw_if_result_is_noth { if (min_mantissa_bits_of_floating <= 24) return std::make_shared(); - else if (min_mantissa_bits_of_floating <= 53) + if (min_mantissa_bits_of_floating <= 53) return std::make_shared(); - else - throw Exception(ErrorCodes::NO_COMMON_TYPE, - "Logical error: {} but as all data types are floats, " - "we must have found maximum float type", getExceptionMessagePrefix(types)); + throw Exception( + ErrorCodes::NO_COMMON_TYPE, + "Logical error: {} but as all data types are floats, " + "we must have found maximum float type", + getExceptionMessagePrefix(types)); } /// If there are signed and unsigned types of same bit-width, the result must be unsigned number. @@ -329,41 +330,42 @@ DataTypePtr getMostSubtype(const DataTypes & types, bool throw_if_result_is_noth { if (min_bits_of_unsigned_integer <= 8) return std::make_shared(); - else if (min_bits_of_unsigned_integer <= 16) + if (min_bits_of_unsigned_integer <= 16) return std::make_shared(); - else if (min_bits_of_unsigned_integer <= 32) + if (min_bits_of_unsigned_integer <= 32) return std::make_shared(); - else if (min_bits_of_unsigned_integer <= 64) + if (min_bits_of_unsigned_integer <= 64) return std::make_shared(); - else if (min_bits_of_unsigned_integer <= 128) + if (min_bits_of_unsigned_integer <= 128) return std::make_shared(); - else if (min_bits_of_unsigned_integer <= 256) + if (min_bits_of_unsigned_integer <= 256) return std::make_shared(); - else - throw Exception(ErrorCodes::NO_COMMON_TYPE, - "Logical error: {} but as all data types are integers, " - "we must have found maximum unsigned integer type", - getExceptionMessagePrefix(types)); + throw Exception( + ErrorCodes::NO_COMMON_TYPE, + "Logical error: {} but as all data types are integers, " + "we must have found maximum unsigned integer type", + getExceptionMessagePrefix(types)); } /// All signed. { if (min_bits_of_signed_integer <= 8) return std::make_shared(); - else if (min_bits_of_signed_integer <= 16) + if (min_bits_of_signed_integer <= 16) return std::make_shared(); - else if (min_bits_of_signed_integer <= 32) + if (min_bits_of_signed_integer <= 32) return std::make_shared(); - else if (min_bits_of_signed_integer <= 64) + if (min_bits_of_signed_integer <= 64) return std::make_shared(); - else if (min_bits_of_signed_integer <= 128) + if (min_bits_of_signed_integer <= 128) return std::make_shared(); - else if (min_bits_of_signed_integer <= 256) + if (min_bits_of_signed_integer <= 256) return std::make_shared(); - else - throw Exception(ErrorCodes::NO_COMMON_TYPE, - "Logical error: {} but as all data types are integers, " - "we must have found maximum signed integer type", getExceptionMessagePrefix(types)); + throw Exception( + ErrorCodes::NO_COMMON_TYPE, + "Logical error: {} but as all data types are integers, " + "we must have found maximum signed integer type", + getExceptionMessagePrefix(types)); } } } diff --git a/src/DataTypes/hasNullable.cpp b/src/DataTypes/hasNullable.cpp index 908b9880473..025b6758e19 100644 --- a/src/DataTypes/hasNullable.cpp +++ b/src/DataTypes/hasNullable.cpp @@ -13,7 +13,7 @@ bool hasNullable(const DataTypePtr & type) if (const DataTypeArray * type_array = typeid_cast(type.get())) return hasNullable(type_array->getNestedType()); - else if (const DataTypeTuple * type_tuple = typeid_cast(type.get())) + if (const DataTypeTuple * type_tuple = typeid_cast(type.get())) { for (const auto & subtype : type_tuple->getElements()) { @@ -22,7 +22,7 @@ bool hasNullable(const DataTypePtr & type) } return false; } - else if (const DataTypeMap * type_map = typeid_cast(type.get())) + if (const DataTypeMap * type_map = typeid_cast(type.get())) { // Key type cannot be nullable. We only check value type. return hasNullable(type_map->getValueType()); diff --git a/src/DataTypes/registerDataTypeDateTime.cpp b/src/DataTypes/registerDataTypeDateTime.cpp index 9a632bd381b..898a14dd459 100644 --- a/src/DataTypes/registerDataTypeDateTime.cpp +++ b/src/DataTypes/registerDataTypeDateTime.cpp @@ -49,9 +49,9 @@ getArgument(const ASTPtr & arguments, size_t argument_index, const char * argume if (argument && argument->value.getType() != field_type) throw Exception(getExceptionMessage(fmt::format(" has wrong type: {}", argument->value.getTypeName()), argument_index, argument_name, context_data_type_name, field_type), ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); - else - throw Exception(getExceptionMessage(" is missing", argument_index, argument_name, context_data_type_name, field_type), - ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); + throw Exception( + getExceptionMessage(" is missing", argument_index, argument_name, context_data_type_name, field_type), + ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); } } diff --git a/src/Databases/DatabaseFactory.cpp b/src/Databases/DatabaseFactory.cpp index b58b63861ab..28bb9825614 100644 --- a/src/Databases/DatabaseFactory.cpp +++ b/src/Databases/DatabaseFactory.cpp @@ -96,8 +96,7 @@ DatabasePtr DatabaseFactory::get(const ASTCreateQuery & create, const String & m auto hints = getHints(engine_name); if (!hints.empty()) throw Exception(ErrorCodes::UNKNOWN_DATABASE_ENGINE, "Unknown database engine {}. Maybe you meant: {}", engine_name, toString(hints)); - else - throw Exception(ErrorCodes::UNKNOWN_DATABASE_ENGINE, "Unknown database engine: {}", create.storage->engine->name); + throw Exception(ErrorCodes::UNKNOWN_DATABASE_ENGINE, "Unknown database engine: {}", create.storage->engine->name); } /// if the engine is found (i.e. registered with the factory instance), then validate if the diff --git a/src/Databases/DatabaseFilesystem.cpp b/src/Databases/DatabaseFilesystem.cpp index 417230e427a..f3a280e9a2b 100644 --- a/src/Databases/DatabaseFilesystem.cpp +++ b/src/Databases/DatabaseFilesystem.cpp @@ -97,16 +97,14 @@ bool DatabaseFilesystem::checkTableFilePath(const std::string & table_path, Cont { if (throw_on_error) throw Exception(ErrorCodes::FILE_DOESNT_EXIST, "File does not exist: {}", table_path); - else - return false; + return false; } if (!fs::is_regular_file(table_path)) { if (throw_on_error) throw Exception(ErrorCodes::FILE_DOESNT_EXIST, "File is directory, but expected a file: {}", table_path); - else - return false; + return false; } } diff --git a/src/Databases/DatabaseMemory.cpp b/src/Databases/DatabaseMemory.cpp index 86bf0471b8f..2ab09366f78 100644 --- a/src/Databases/DatabaseMemory.cpp +++ b/src/Databases/DatabaseMemory.cpp @@ -120,8 +120,7 @@ ASTPtr DatabaseMemory::getCreateTableQueryImpl(const String & table_name, Contex { if (throw_on_error) throw Exception(ErrorCodes::UNKNOWN_TABLE, "There is no metadata of table {} in database {}", table_name, database_name); - else - return {}; + return {}; } return it->second->clone(); } diff --git a/src/Databases/DatabaseOnDisk.cpp b/src/Databases/DatabaseOnDisk.cpp index dfade31ac1b..942ba602d92 100644 --- a/src/Databases/DatabaseOnDisk.cpp +++ b/src/Databases/DatabaseOnDisk.cpp @@ -319,14 +319,13 @@ void DatabaseOnDisk::detachTablePermanently(ContextPtr query_context, const Stri FS::createFile(detached_permanently_flag); std::lock_guard lock(mutex); - if (const auto it = snapshot_detached_tables.find(table_name); it == snapshot_detached_tables.end()) + const auto it = snapshot_detached_tables.find(table_name); + if (it == snapshot_detached_tables.end()) { throw Exception(ErrorCodes::LOGICAL_ERROR, "Snapshot doesn't contain info about detached table `{}`", table_name); } - else - { - it->second.is_permanently = true; - } + + it->second.is_permanently = true; } catch (Exception & e) { @@ -397,9 +396,8 @@ void DatabaseOnDisk::checkMetadataFilenameAvailabilityUnlocked(const String & to if (fs::exists(detached_permanently_flag)) throw Exception(ErrorCodes::TABLE_ALREADY_EXISTS, "Table {}.{} already exists (detached permanently)", backQuote(database_name), backQuote(to_table_name)); - else - throw Exception(ErrorCodes::TABLE_ALREADY_EXISTS, "Table {}.{} already exists (detached)", - backQuote(database_name), backQuote(to_table_name)); + throw Exception( + ErrorCodes::TABLE_ALREADY_EXISTS, "Table {}.{} already exists (detached)", backQuote(database_name), backQuote(to_table_name)); } } @@ -530,7 +528,7 @@ ASTPtr DatabaseOnDisk::getCreateTableQueryImpl(const String & table_name, Contex { if (!has_table && e.code() == ErrorCodes::FILE_DOESNT_EXIST && throw_on_error) throw Exception(ErrorCodes::CANNOT_GET_CREATE_TABLE_QUERY, "Table {} doesn't exist", backQuote(table_name)); - else if (!is_system_storage && throw_on_error) + if (!is_system_storage && throw_on_error) throw; } if (!ast && is_system_storage) @@ -617,8 +615,7 @@ time_t DatabaseOnDisk::getObjectMetadataModificationTime(const String & object_n { return static_cast(0); } - else - throw; + throw; } } @@ -763,7 +760,7 @@ ASTPtr DatabaseOnDisk::parseQueryFromMetadata( if (!ast && throw_on_error) throw Exception::createDeprecated(error_message, ErrorCodes::SYNTAX_ERROR); - else if (!ast) + if (!ast) return nullptr; auto & create = ast->as(); @@ -806,8 +803,7 @@ ASTPtr DatabaseOnDisk::getCreateQueryFromStorage(const String & table_name, cons if (throw_on_error) throw Exception(ErrorCodes::CANNOT_GET_CREATE_TABLE_QUERY, "Cannot get metadata of {}.{}", backQuote(getDatabaseName()), backQuote(table_name)); - else - return nullptr; + return nullptr; } /// setup create table query storage info. diff --git a/src/Databases/DatabaseReplicated.cpp b/src/Databases/DatabaseReplicated.cpp index d5b242180fc..ef73964d009 100644 --- a/src/Databases/DatabaseReplicated.cpp +++ b/src/Databases/DatabaseReplicated.cpp @@ -643,7 +643,8 @@ void DatabaseReplicated::createReplicaNodesInZooKeeper(const zkutil::ZooKeeperPt { nodes_exist = false; break; - } else if (response.error != Coordination::Error::ZOK) + } + if (response.error != Coordination::Error::ZOK) { throw zkutil::KeeperException::fromPath(response.error, check_paths[i]); } @@ -1216,7 +1217,7 @@ void DatabaseReplicated::recoverLostReplica(const ZooKeeperPtr & current_zookeep String to_db_name_replicated = getDatabaseName() + BROKEN_REPLICATED_TABLES_SUFFIX; if (total_tables * db_settings.max_broken_tables_ratio < tables_to_detach.size()) throw Exception(ErrorCodes::DATABASE_REPLICATION_FAILED, "Too many tables to recreate: {} of {}", tables_to_detach.size(), total_tables); - else if (!tables_to_detach.empty()) + if (!tables_to_detach.empty()) { LOG_WARNING(log, "Will recreate {} broken tables to recover replica", tables_to_detach.size()); /// It's too dangerous to automatically drop tables, so we will move them to special database. @@ -1225,14 +1226,14 @@ void DatabaseReplicated::recoverLostReplica(const ZooKeeperPtr & current_zookeep String query = fmt::format("CREATE DATABASE IF NOT EXISTS {} ENGINE=Ordinary", backQuoteIfNeed(to_db_name)); auto query_context = Context::createCopy(getContext()); query_context->setSetting("allow_deprecated_database_ordinary", 1); - executeQuery(query, query_context, QueryFlags{ .internal = true }); + executeQuery(query, query_context, QueryFlags{.internal = true}); /// But we want to avoid discarding UUID of ReplicatedMergeTree tables, because it will not work /// if zookeeper_path contains {uuid} macro. Replicated database do not recreate replicated tables on recovery, /// so it's ok to save UUID of replicated table. query = fmt::format("CREATE DATABASE IF NOT EXISTS {} ENGINE=Atomic", backQuoteIfNeed(to_db_name_replicated)); query_context = Context::createCopy(getContext()); - executeQuery(query, query_context, QueryFlags{ .internal = true }); + executeQuery(query, query_context, QueryFlags{.internal = true}); } size_t moved_tables = 0; diff --git a/src/Databases/DatabaseReplicatedWorker.cpp b/src/Databases/DatabaseReplicatedWorker.cpp index 4b1d4d6d707..368559c057f 100644 --- a/src/Databases/DatabaseReplicatedWorker.cpp +++ b/src/Databases/DatabaseReplicatedWorker.cpp @@ -257,7 +257,7 @@ String DatabaseReplicatedDDLWorker::enqueueQueryImpl(const ZooKeeperPtr & zookee counter_path = dynamic_cast(*res[1]).path_created; break; } - else if (res[0]->error != Coordination::Error::ZNODEEXISTS) + if (res[0]->error != Coordination::Error::ZNODEEXISTS) zkutil::KeeperMultiException::check(code, ops, res); sleepForMilliseconds(50); diff --git a/src/Databases/DatabasesCommon.cpp b/src/Databases/DatabasesCommon.cpp index d8151cf340a..14fc5a9a691 100644 --- a/src/Databases/DatabasesCommon.cpp +++ b/src/Databases/DatabasesCommon.cpp @@ -128,8 +128,7 @@ ASTPtr getCreateQueryFromStorage(const StoragePtr & storage, const ASTPtr & ast_ if (throw_on_error) throw Exception(ErrorCodes::CANNOT_GET_CREATE_TABLE_QUERY, "Cannot get metadata of {}.{}", backQuote(table_id.database_name), backQuote(table_id.table_name)); - else - return nullptr; + return nullptr; } auto create_table_query = std::make_shared(); @@ -166,8 +165,7 @@ ASTPtr getCreateQueryFromStorage(const StoragePtr & storage, const ASTPtr & ast_ if (throw_on_error) throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot parse metadata of {}.{}", backQuote(table_id.database_name), backQuote(table_id.table_name)); - else - return nullptr; + return nullptr; } ast_column_declaration->type = ast_type; diff --git a/src/Databases/IDatabase.cpp b/src/Databases/IDatabase.cpp index 95d671d1960..58d1ad0d98c 100644 --- a/src/Databases/IDatabase.cpp +++ b/src/Databases/IDatabase.cpp @@ -35,14 +35,13 @@ StoragePtr IDatabase::getTable(const String & name, ContextPtr context) const if (hint.first.empty()) throw Exception(ErrorCodes::UNKNOWN_TABLE, "Table {}.{} does not exist", backQuoteIfNeed(getDatabaseName()), backQuoteIfNeed(name)); - else - throw Exception( - ErrorCodes::UNKNOWN_TABLE, - "Table {}.{} does not exist. Maybe you meant {}.{}?", - backQuoteIfNeed(getDatabaseName()), - backQuoteIfNeed(name), - backQuoteIfNeed(hint.first), - backQuoteIfNeed(hint.second)); + throw Exception( + ErrorCodes::UNKNOWN_TABLE, + "Table {}.{} does not exist. Maybe you meant {}.{}?", + backQuoteIfNeed(getDatabaseName()), + backQuoteIfNeed(name), + backQuoteIfNeed(hint.first), + backQuoteIfNeed(hint.second)); } IDatabase::IDatabase(String database_name_) : database_name(std::move(database_name_)) diff --git a/src/Databases/MySQL/MaterializedMySQLSyncThread.cpp b/src/Databases/MySQL/MaterializedMySQLSyncThread.cpp index b1679fcf94f..0609f3eabbf 100644 --- a/src/Databases/MySQL/MaterializedMySQLSyncThread.cpp +++ b/src/Databases/MySQL/MaterializedMySQLSyncThread.cpp @@ -387,10 +387,9 @@ void MaterializedMySQLSyncThread::assertMySQLAvailable() throw Exception(ErrorCodes::SYNC_MYSQL_USER_ACCESS_ERROR, "MySQL SYNC USER ACCESS ERR: " "mysql sync user needs at least GLOBAL PRIVILEGES:'RELOAD, REPLICATION SLAVE, REPLICATION CLIENT' " "and SELECT PRIVILEGE on Database {}", mysql_database_name); - else if (e.errnum() == ER_BAD_DB_ERROR) + if (e.errnum() == ER_BAD_DB_ERROR) throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Unknown database '{}' on MySQL", mysql_database_name); - else - throw; + throw; } } diff --git a/src/Databases/MySQL/MySQLBinlog.cpp b/src/Databases/MySQL/MySQLBinlog.cpp index 3e3aca220bb..63adf591c90 100644 --- a/src/Databases/MySQL/MySQLBinlog.cpp +++ b/src/Databases/MySQL/MySQLBinlog.cpp @@ -302,7 +302,7 @@ void BinlogFromSocket::handshake(const String & user, const String & password) if (packet_response.getType() == PACKET_ERR) throw Exception::createDeprecated(packet_response.err.error_message, ErrorCodes::UNKNOWN_PACKET_FROM_SERVER); - else if (packet_response.getType() == PACKET_AUTH_SWITCH) + if (packet_response.getType() == PACKET_AUTH_SWITCH) throw Exception(ErrorCodes::UNKNOWN_PACKET_FROM_SERVER, "Access denied for user {}", user); } diff --git a/src/Databases/SQLite/SQLiteUtils.cpp b/src/Databases/SQLite/SQLiteUtils.cpp index eeea04476d3..8a78f755a37 100644 --- a/src/Databases/SQLite/SQLiteUtils.cpp +++ b/src/Databases/SQLite/SQLiteUtils.cpp @@ -20,8 +20,7 @@ void processSQLiteError(const String & message, bool throw_on_error) { if (throw_on_error) throw Exception::createDeprecated(message, ErrorCodes::PATH_ACCESS_DENIED); - else - LOG_ERROR(getLogger("SQLiteEngine"), fmt::runtime(message)); + LOG_ERROR(getLogger("SQLiteEngine"), fmt::runtime(message)); } String validateSQLiteDatabasePath(const String & path, const String & user_files_path, bool need_check, bool throw_on_error) diff --git a/src/Dictionaries/CacheDictionary.cpp b/src/Dictionaries/CacheDictionary.cpp index 1816324a93b..93526078dab 100644 --- a/src/Dictionaries/CacheDictionary.cpp +++ b/src/Dictionaries/CacheDictionary.cpp @@ -130,12 +130,10 @@ ColumnPtr CacheDictionary::getColumn( IColumn::Filter & default_mask = std::get(default_or_filter).get(); return getColumns({attribute_name}, {attribute_type}, key_columns, key_types, default_mask).front(); } - else - { - const ColumnPtr & default_values_column = std::get(default_or_filter).get(); - const Columns & columns= Columns({default_values_column}); - return getColumns({attribute_name}, {attribute_type}, key_columns, key_types, columns).front(); - } + + const ColumnPtr & default_values_column = std::get(default_or_filter).get(); + const Columns & columns = Columns({default_values_column}); + return getColumns({attribute_name}, {attribute_type}, key_columns, key_types, columns).front(); } template @@ -209,18 +207,12 @@ Columns CacheDictionary::getColumns( if (source_returns_fetched_columns_in_order_of_keys) return request.filterRequestedColumns(fetched_columns_from_storage); - else - { - /// Reorder result from storage to requested keys indexes - MutableColumns aggregated_columns = aggregateColumnsInOrderOfKeys( - keys, - request, - fetched_columns_from_storage, - key_index_to_state_from_storage, - default_mask); - return request.filterRequestedColumns(aggregated_columns); - } + /// Reorder result from storage to requested keys indexes + MutableColumns aggregated_columns + = aggregateColumnsInOrderOfKeys(keys, request, fetched_columns_from_storage, key_index_to_state_from_storage, default_mask); + + return request.filterRequestedColumns(aggregated_columns); } size_t keys_to_update_size = not_found_keys_size + expired_keys_size; @@ -237,30 +229,22 @@ Columns CacheDictionary::getColumns( if (source_returns_fetched_columns_in_order_of_keys) return request.filterRequestedColumns(fetched_columns_from_storage); - else - { - /// Reorder result from storage to requested keys indexes - MutableColumns aggregated_columns = aggregateColumnsInOrderOfKeys( - keys, - request, - fetched_columns_from_storage, - key_index_to_state_from_storage, - default_mask); - return request.filterRequestedColumns(aggregated_columns); - } - } - else - { - /// Start sync update - update_queue.tryPushToUpdateQueueOrThrow(update_unit); - update_queue.waitForCurrentUpdateFinish(update_unit); + /// Reorder result from storage to requested keys indexes + MutableColumns aggregated_columns + = aggregateColumnsInOrderOfKeys(keys, request, fetched_columns_from_storage, key_index_to_state_from_storage, default_mask); - requested_keys_to_fetched_columns_during_update_index = - std::move(update_unit->requested_keys_to_fetched_columns_during_update_index); - fetched_columns_during_update = std::move(update_unit->fetched_columns_during_update); + return request.filterRequestedColumns(aggregated_columns); } + /// Start sync update + update_queue.tryPushToUpdateQueueOrThrow(update_unit); + update_queue.waitForCurrentUpdateFinish(update_unit); + + requested_keys_to_fetched_columns_during_update_index = std::move(update_unit->requested_keys_to_fetched_columns_during_update_index); + fetched_columns_during_update = std::move(update_unit->fetched_columns_during_update); + + MutableColumns aggregated_columns = aggregateColumns( keys, request, @@ -395,8 +379,7 @@ ColumnPtr CacheDictionary::getHierarchy( found_count.fetch_add(keys_found, std::memory_order_relaxed); return result; } - else - return nullptr; + return nullptr; } template @@ -413,8 +396,7 @@ ColumnUInt8::Ptr CacheDictionary::isInHierarchy( found_count.fetch_add(keys_found, std::memory_order_relaxed); return result; } - else - return nullptr; + return nullptr; } template diff --git a/src/Dictionaries/CacheDictionaryStorage.h b/src/Dictionaries/CacheDictionaryStorage.h index 8c9f59cc112..3208a1e0e7e 100644 --- a/src/Dictionaries/CacheDictionaryStorage.h +++ b/src/Dictionaries/CacheDictionaryStorage.h @@ -64,8 +64,7 @@ public: { if (dictionary_key_type == DictionaryKeyType::Simple) return "Cache"; - else - return "ComplexKeyCache"; + return "ComplexKeyCache"; } bool supportsSimpleKeys() const override { return dictionary_key_type == DictionaryKeyType::Simple; } diff --git a/src/Dictionaries/ClickHouseDictionarySource.cpp b/src/Dictionaries/ClickHouseDictionarySource.cpp index c902fe81fda..dda9e72afa7 100644 --- a/src/Dictionaries/ClickHouseDictionarySource.cpp +++ b/src/Dictionaries/ClickHouseDictionarySource.cpp @@ -104,11 +104,9 @@ std::string ClickHouseDictionarySource::getUpdateFieldAndDate() update_time = std::chrono::system_clock::now(); return query_builder->composeUpdateQuery(configuration.update_field, str_time); } - else - { - update_time = std::chrono::system_clock::now(); - return query_builder->composeLoadAllQuery(); - } + + update_time = std::chrono::system_clock::now(); + return query_builder->composeLoadAllQuery(); } QueryPipeline ClickHouseDictionarySource::loadAll() @@ -195,14 +193,12 @@ std::string ClickHouseDictionarySource::doInvalidateQuery(const std::string & re { return readInvalidateQuery(executeQuery(request, context_copy, QueryFlags{ .internal = true }).second.pipeline); } - else - { - /// We pass empty block to RemoteQueryExecutor, because we don't know the structure of the result. - Block invalidate_sample_block; - QueryPipeline pipeline(std::make_shared( - std::make_shared(pool, request, invalidate_sample_block, context_copy), false, false, false)); - return readInvalidateQuery(std::move(pipeline)); - } + + /// We pass empty block to RemoteQueryExecutor, because we don't know the structure of the result. + Block invalidate_sample_block; + QueryPipeline pipeline(std::make_shared( + std::make_shared(pool, request, invalidate_sample_block, context_copy), false, false, false)); + return readInvalidateQuery(std::move(pipeline)); } void registerDictionarySourceClickHouse(DictionarySourceFactory & factory) diff --git a/src/Dictionaries/DictionaryHelpers.h b/src/Dictionaries/DictionaryHelpers.h index 43fd39640c3..04828d4d76f 100644 --- a/src/Dictionaries/DictionaryHelpers.h +++ b/src/Dictionaries/DictionaryHelpers.h @@ -274,10 +274,8 @@ public: auto nested_column = array_type->getNestedType()->createColumn(); return ColumnArray::create(std::move(nested_column)); } - else - { - throw Exception(ErrorCodes::TYPE_MISMATCH, "Unsupported attribute type."); - } + + throw Exception(ErrorCodes::TYPE_MISMATCH, "Unsupported attribute type."); } if constexpr (std::is_same_v) { @@ -681,10 +679,8 @@ static const PaddedPODArray & getColumnVectorData( return backup_storage; } - else - { - return vector_col->getData(); - } + + return vector_col->getData(); } template diff --git a/src/Dictionaries/DictionaryStructure.cpp b/src/Dictionaries/DictionaryStructure.cpp index bd9ec57af1f..a1224b8a36d 100644 --- a/src/Dictionaries/DictionaryStructure.cpp +++ b/src/Dictionaries/DictionaryStructure.cpp @@ -109,7 +109,7 @@ DictionaryStructure::DictionaryStructure(const Poco::Util::AbstractConfiguration throw Exception(ErrorCodes::TYPE_MISMATCH, "Hierarchical attribute type for dictionary with simple key must be UInt64. Actual {}", attribute.underlying_type); - else if (key) + if (key) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Dictionary with complex key does not support hierarchy"); hierarchical_attribute_index = i; @@ -203,8 +203,7 @@ size_t DictionaryStructure::getKeysSize() const { if (id) return 1; - else - return key->size(); + return key->size(); } std::string DictionaryStructure::getKeyDescription() const diff --git a/src/Dictionaries/DirectDictionary.cpp b/src/Dictionaries/DirectDictionary.cpp index 79e5857ec69..29d41133b74 100644 --- a/src/Dictionaries/DirectDictionary.cpp +++ b/src/Dictionaries/DirectDictionary.cpp @@ -216,12 +216,10 @@ ColumnPtr DirectDictionary::getColumn( IColumn::Filter & default_mask = std::get(default_or_filter).get(); return getColumns({attribute_name}, {attribute_type}, key_columns, key_types, default_mask).front(); } - else - { - const ColumnPtr & default_values_column = std::get(default_or_filter).get(); - const Columns & columns= Columns({default_values_column}); - return getColumns({attribute_name}, {attribute_type}, key_columns, key_types, columns).front(); - } + + const ColumnPtr & default_values_column = std::get(default_or_filter).get(); + const Columns & columns = Columns({default_values_column}); + return getColumns({attribute_name}, {attribute_type}, key_columns, key_types, columns).front(); } template @@ -307,8 +305,7 @@ ColumnPtr DirectDictionary::getHierarchy( found_count.fetch_add(keys_found, std::memory_order_relaxed); return result; } - else - return nullptr; + return nullptr; } template @@ -325,8 +322,7 @@ ColumnUInt8::Ptr DirectDictionary::isInHierarchy( found_count.fetch_add(keys_found, std::memory_order_relaxed); return result; } - else - return nullptr; + return nullptr; } template diff --git a/src/Dictionaries/Embedded/GeodataProviders/NamesProvider.cpp b/src/Dictionaries/Embedded/GeodataProviders/NamesProvider.cpp index e6a8d308e87..4b93129c526 100644 --- a/src/Dictionaries/Embedded/GeodataProviders/NamesProvider.cpp +++ b/src/Dictionaries/Embedded/GeodataProviders/NamesProvider.cpp @@ -46,8 +46,7 @@ ILanguageRegionsNamesDataSourcePtr RegionsNamesDataProvider::getLanguageRegionsN const auto data_file = getDataFilePath(language); if (fs::exists(data_file)) return std::make_unique(data_file, language); - else - return {}; + return {}; } std::string RegionsNamesDataProvider::getDataFilePath(const std::string & language) const diff --git a/src/Dictionaries/ExternalQueryBuilder.cpp b/src/Dictionaries/ExternalQueryBuilder.cpp index 0b8b888fcbb..92638ffcc6b 100644 --- a/src/Dictionaries/ExternalQueryBuilder.cpp +++ b/src/Dictionaries/ExternalQueryBuilder.cpp @@ -214,29 +214,27 @@ std::string ExternalQueryBuilder::composeUpdateQuery(const std::string & update_ return out.str(); } - else + + writeString(query, out); + + auto condition_position = query.find(CONDITION_PLACEHOLDER_TO_REPLACE_VALUE); + if (condition_position == std::string::npos) { - writeString(query, out); + writeString(" WHERE ", out); + composeUpdateCondition(update_field, time_point, out); + writeString(";", out); - auto condition_position = query.find(CONDITION_PLACEHOLDER_TO_REPLACE_VALUE); - if (condition_position == std::string::npos) - { - writeString(" WHERE ", out); - composeUpdateCondition(update_field, time_point, out); - writeString(";", out); - - return out.str(); - } - - WriteBufferFromOwnString condition_value_buffer; - composeUpdateCondition(update_field, time_point, condition_value_buffer); - const auto & condition_value = condition_value_buffer.str(); - - auto query_copy = query; - query_copy.replace(condition_position, CONDITION_PLACEHOLDER_TO_REPLACE_VALUE.size(), condition_value); - - return query_copy; + return out.str(); } + + WriteBufferFromOwnString condition_value_buffer; + composeUpdateCondition(update_field, time_point, condition_value_buffer); + const auto & condition_value = condition_value_buffer.str(); + + auto query_copy = query; + query_copy.replace(condition_position, CONDITION_PLACEHOLDER_TO_REPLACE_VALUE.size(), condition_value); + + return query_copy; } @@ -299,29 +297,27 @@ std::string ExternalQueryBuilder::composeLoadIdsQuery(const std::vector return out.str(); } - else + + writeString(query, out); + + auto condition_position = query.find(CONDITION_PLACEHOLDER_TO_REPLACE_VALUE); + if (condition_position == std::string::npos) { - writeString(query, out); + writeString(" WHERE ", out); + composeIdsCondition(ids, out); + writeString(";", out); - auto condition_position = query.find(CONDITION_PLACEHOLDER_TO_REPLACE_VALUE); - if (condition_position == std::string::npos) - { - writeString(" WHERE ", out); - composeIdsCondition(ids, out); - writeString(";", out); - - return out.str(); - } - - WriteBufferFromOwnString condition_value_buffer; - composeIdsCondition(ids, condition_value_buffer); - const auto & condition_value = condition_value_buffer.str(); - - auto query_copy = query; - query_copy.replace(condition_position, CONDITION_PLACEHOLDER_TO_REPLACE_VALUE.size(), condition_value); - - return query_copy; + return out.str(); } + + WriteBufferFromOwnString condition_value_buffer; + composeIdsCondition(ids, condition_value_buffer); + const auto & condition_value = condition_value_buffer.str(); + + auto query_copy = query; + query_copy.replace(condition_position, CONDITION_PLACEHOLDER_TO_REPLACE_VALUE.size(), condition_value); + + return query_copy; } @@ -390,31 +386,29 @@ std::string ExternalQueryBuilder::composeLoadKeysQuery( return out.str(); } - else + + auto condition_position = query.find(CONDITION_PLACEHOLDER_TO_REPLACE_VALUE); + if (condition_position == std::string::npos) { - auto condition_position = query.find(CONDITION_PLACEHOLDER_TO_REPLACE_VALUE); - if (condition_position == std::string::npos) - { - writeString("SELECT * FROM (", out); - writeString(query, out); - writeString(") AS subquery WHERE ", out); - composeKeysCondition(key_columns, requested_rows, method, partition_key_prefix, out); - writeString(";", out); - - return out.str(); - } - + writeString("SELECT * FROM (", out); writeString(query, out); + writeString(") AS subquery WHERE ", out); + composeKeysCondition(key_columns, requested_rows, method, partition_key_prefix, out); + writeString(";", out); - WriteBufferFromOwnString condition_value_buffer; - composeKeysCondition(key_columns, requested_rows, method, partition_key_prefix, condition_value_buffer); - const auto & condition_value = condition_value_buffer.str(); - - auto query_copy = query; - query_copy.replace(condition_position, CONDITION_PLACEHOLDER_TO_REPLACE_VALUE.size(), condition_value); - - return query_copy; + return out.str(); } + + writeString(query, out); + + WriteBufferFromOwnString condition_value_buffer; + composeKeysCondition(key_columns, requested_rows, method, partition_key_prefix, condition_value_buffer); + const auto & condition_value = condition_value_buffer.str(); + + auto query_copy = query; + query_copy.replace(condition_position, CONDITION_PLACEHOLDER_TO_REPLACE_VALUE.size(), condition_value); + + return query_copy; } diff --git a/src/Dictionaries/HashedArrayDictionary.cpp b/src/Dictionaries/HashedArrayDictionary.cpp index 83350af2fff..d12cffb50fa 100644 --- a/src/Dictionaries/HashedArrayDictionary.cpp +++ b/src/Dictionaries/HashedArrayDictionary.cpp @@ -1151,7 +1151,7 @@ void registerDictionaryArrayHashed(DictionaryFactory & factory) { if (dictionary_key_type == DictionaryKeyType::Simple && dict_struct.key) throw Exception(ErrorCodes::UNSUPPORTED_METHOD, "'key' is not supported for simple key hashed array dictionary"); - else if (dictionary_key_type == DictionaryKeyType::Complex && dict_struct.id) + if (dictionary_key_type == DictionaryKeyType::Complex && dict_struct.id) throw Exception(ErrorCodes::UNSUPPORTED_METHOD, "'id' is not supported for complex key hashed array dictionary"); if (dict_struct.range_min || dict_struct.range_max) @@ -1195,12 +1195,12 @@ void registerDictionaryArrayHashed(DictionaryFactory & factory) return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); } - else - { - if (shards > 1) - return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); - return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); - } + + if (shards > 1) + return std::make_unique>( + dict_id, dict_struct, std::move(source_ptr), configuration); + return std::make_unique>( + dict_id, dict_struct, std::move(source_ptr), configuration); }; factory.registerLayout("hashed_array", diff --git a/src/Dictionaries/HierarchyDictionariesUtils.cpp b/src/Dictionaries/HierarchyDictionariesUtils.cpp index de532ade26d..957d99ba554 100644 --- a/src/Dictionaries/HierarchyDictionariesUtils.cpp +++ b/src/Dictionaries/HierarchyDictionariesUtils.cpp @@ -149,12 +149,10 @@ ColumnPtr getKeysDescendantsArray( auto elements_and_offsets = detail::getDescendants(requested_keys, parent_to_child_index, strategy, valid_keys); return detail::convertElementsAndOffsetsIntoArray(std::move(elements_and_offsets)); } - else - { - detail::GetDescendantsAtSpecificLevelStrategy strategy { .level = level }; - auto elements_and_offsets = detail::getDescendants(requested_keys, parent_to_child_index, strategy, valid_keys); - return detail::convertElementsAndOffsetsIntoArray(std::move(elements_and_offsets)); - } + + detail::GetDescendantsAtSpecificLevelStrategy strategy{.level = level}; + auto elements_and_offsets = detail::getDescendants(requested_keys, parent_to_child_index, strategy, valid_keys); + return detail::convertElementsAndOffsetsIntoArray(std::move(elements_and_offsets)); } ColumnPtr getKeysHierarchyDefaultImplementation( diff --git a/src/Dictionaries/MySQLDictionarySource.cpp b/src/Dictionaries/MySQLDictionarySource.cpp index a42ccb4f22c..ea403fc3431 100644 --- a/src/Dictionaries/MySQLDictionarySource.cpp +++ b/src/Dictionaries/MySQLDictionarySource.cpp @@ -217,11 +217,9 @@ std::string MySQLDictionarySource::getUpdateFieldAndDate() update_time = std::chrono::system_clock::now(); return query_builder.composeUpdateQuery(configuration.update_field, str_time); } - else - { - update_time = std::chrono::system_clock::now(); - return load_all_query; - } + + update_time = std::chrono::system_clock::now(); + return load_all_query; } QueryPipeline MySQLDictionarySource::loadFromQuery(const String & query) diff --git a/src/Dictionaries/PostgreSQLDictionarySource.cpp b/src/Dictionaries/PostgreSQLDictionarySource.cpp index b5b83370dc6..fbf199567b3 100644 --- a/src/Dictionaries/PostgreSQLDictionarySource.cpp +++ b/src/Dictionaries/PostgreSQLDictionarySource.cpp @@ -161,11 +161,9 @@ std::string PostgreSQLDictionarySource::getUpdateFieldAndDate() update_time = std::chrono::system_clock::now(); return query_builder.composeUpdateQuery(configuration.update_field, str_time); } - else - { - update_time = std::chrono::system_clock::now(); - return query_builder.composeLoadAllQuery(); - } + + update_time = std::chrono::system_clock::now(); + return query_builder.composeLoadAllQuery(); } diff --git a/src/Dictionaries/RegExpTreeDictionary.cpp b/src/Dictionaries/RegExpTreeDictionary.cpp index f5ff50aba8a..214158c40d3 100644 --- a/src/Dictionaries/RegExpTreeDictionary.cpp +++ b/src/Dictionaries/RegExpTreeDictionary.cpp @@ -375,8 +375,8 @@ void RegExpTreeDictionary::loadData() if (error->expression < 0) throw Exception::createRuntime(ErrorCodes::LOGICAL_ERROR, String(error->message)); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Pattern '{}' failed with error '{}'", patterns[error->expression], String(error->message)); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, "Pattern '{}' failed with error '{}'", patterns[error->expression], String(error->message)); } /// We allocate the scratch space only once, then copy it across multiple threads with hs_clone_scratch @@ -491,10 +491,8 @@ public: return false; return it->second.safeGet().size() >= *collect_values_limit; } - else - { - return this->contains(attr_name) || (defaults && defaults->contains(attr_name)); - } + + return this->contains(attr_name) || (defaults && defaults->contains(attr_name)); } // Returns the number of full attributes diff --git a/src/Dictionaries/RegExpTreeDictionary.h b/src/Dictionaries/RegExpTreeDictionary.h index 7348c9b9257..fb92ee4c9dd 100644 --- a/src/Dictionaries/RegExpTreeDictionary.h +++ b/src/Dictionaries/RegExpTreeDictionary.h @@ -114,12 +114,10 @@ public: IColumn::Filter & default_mask = std::get(default_or_filter).get(); return getColumns({attribute_name}, {attribute_type}, key_columns, key_types, default_mask).front(); } - else - { - const ColumnPtr & default_values_column = std::get(default_or_filter).get(); - const Columns & columns= Columns({default_values_column}); - return getColumns({attribute_name}, {attribute_type}, key_columns, key_types, columns).front(); - } + + const ColumnPtr & default_values_column = std::get(default_or_filter).get(); + const Columns & columns = Columns({default_values_column}); + return getColumns({attribute_name}, {attribute_type}, key_columns, key_types, columns).front(); } Columns getColumns( diff --git a/src/Dictionaries/SSDCacheDictionaryStorage.h b/src/Dictionaries/SSDCacheDictionaryStorage.h index 2b53b59bdac..444d189132d 100644 --- a/src/Dictionaries/SSDCacheDictionaryStorage.h +++ b/src/Dictionaries/SSDCacheDictionaryStorage.h @@ -860,8 +860,8 @@ public: { if (dictionary_key_type == DictionaryKeyType::Simple) return "SSDCache"; - else - return "SSDComplexKeyCache"; + + return "SSDComplexKeyCache"; } bool supportsSimpleKeys() const override { return dictionary_key_type == DictionaryKeyType::Simple; } @@ -1244,6 +1244,7 @@ private: SSDCacheIndex cache_index {0, 0}; + /// NOLINTBEGIN(readability-else-after-return) while (true) { bool started_reusing_old_partitions = memory_buffer_partitions.size() == configuration.max_partitions_count; @@ -1364,6 +1365,7 @@ private: } } } + /// NOLINTEND(readability-else-after-return) } void setCellDeadline(Cell & cell, TimePoint now) diff --git a/src/Dictionaries/XDBCDictionarySource.cpp b/src/Dictionaries/XDBCDictionarySource.cpp index 63e2c8766d5..47b837c49bf 100644 --- a/src/Dictionaries/XDBCDictionarySource.cpp +++ b/src/Dictionaries/XDBCDictionarySource.cpp @@ -118,11 +118,9 @@ std::string XDBCDictionarySource::getUpdateFieldAndDate() update_time = std::chrono::system_clock::now(); return query_builder.composeUpdateQuery(configuration.update_field, str_time); } - else - { - update_time = std::chrono::system_clock::now(); - return load_all_query; - } + + update_time = std::chrono::system_clock::now(); + return load_all_query; } diff --git a/src/Dictionaries/registerHashedDictionary.cpp b/src/Dictionaries/registerHashedDictionary.cpp index c571989a641..d0015056ebc 100644 --- a/src/Dictionaries/registerHashedDictionary.cpp +++ b/src/Dictionaries/registerHashedDictionary.cpp @@ -32,7 +32,7 @@ void registerDictionaryHashed(DictionaryFactory & factory) { if (dictionary_key_type == DictionaryKeyType::Simple && dict_struct.key) throw Exception(ErrorCodes::UNSUPPORTED_METHOD, "'key' is not supported for simple key hashed dictionary"); - else if (dictionary_key_type == DictionaryKeyType::Complex && dict_struct.id) + if (dictionary_key_type == DictionaryKeyType::Complex && dict_struct.id) throw Exception(ErrorCodes::UNSUPPORTED_METHOD, "'id' is not supported for complex key hashed dictionary"); if (dict_struct.range_min || dict_struct.range_max) @@ -94,34 +94,31 @@ void registerDictionaryHashed(DictionaryFactory & factory) { if (shards > 1) return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); - else - return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); - } - else - { - if (shards > 1) - return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); - else - return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); + return std::make_unique>( + dict_id, dict_struct, std::move(source_ptr), configuration); } + + if (shards > 1) + return std::make_unique>( + dict_id, dict_struct, std::move(source_ptr), configuration); + return std::make_unique>( + dict_id, dict_struct, std::move(source_ptr), configuration); } - else + + if (sparse) { - if (sparse) - { - if (shards > 1) - return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); - else - return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); - } - else - { - if (shards > 1) - return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); - else - return std::make_unique>(dict_id, dict_struct, std::move(source_ptr), configuration); - } + if (shards > 1) + return std::make_unique>( + dict_id, dict_struct, std::move(source_ptr), configuration); + return std::make_unique>( + dict_id, dict_struct, std::move(source_ptr), configuration); } + + if (shards > 1) + return std::make_unique>( + dict_id, dict_struct, std::move(source_ptr), configuration); + return std::make_unique>( + dict_id, dict_struct, std::move(source_ptr), configuration); }; factory.registerLayout("hashed", diff --git a/src/Disks/DiskEncrypted.cpp b/src/Disks/DiskEncrypted.cpp index 6a91ac2d0fc..d2a7aa381c7 100644 --- a/src/Disks/DiskEncrypted.cpp +++ b/src/Disks/DiskEncrypted.cpp @@ -125,13 +125,13 @@ namespace check_current_key_found(current_key); return current_key; } - else if (config.has(key_hex_path)) + if (config.has(key_hex_path)) { String current_key = unhexKey(config.getString(key_hex_path)); check_current_key_found(current_key); return current_key; } - else if (config.has(key_id_path)) + if (config.has(key_id_path)) { UInt64 current_key_id = config.getUInt64(key_id_path); auto it = keys_by_id.find(current_key_id); @@ -139,15 +139,13 @@ namespace throw Exception(ErrorCodes::BAD_ARGUMENTS, "Not found a key with the current ID {}", current_key_id); return it->second; } - else if (keys_by_id.size() == 1 && keys_without_id.empty() && keys_by_id.begin()->first == 0) + if (keys_by_id.size() == 1 && keys_without_id.empty() && keys_by_id.begin()->first == 0) { /// There is only a single key defined with id=0, so we can choose it as current. return keys_by_id.begin()->second; } - else - { - throw Exception(ErrorCodes::BAD_ARGUMENTS, "The current key is not specified"); - } + + throw Exception(ErrorCodes::BAD_ARGUMENTS, "The current key is not specified"); } /// Reads the current encryption algorithm from the configuration. diff --git a/src/Disks/DiskEncrypted.h b/src/Disks/DiskEncrypted.h index 95bb5ac2a11..990ce7ae0b0 100644 --- a/src/Disks/DiskEncrypted.h +++ b/src/Disks/DiskEncrypted.h @@ -312,10 +312,8 @@ public: { return std::make_shared(*this); } - else - { - return createEncryptedTransaction(); - } + + return createEncryptedTransaction(); } std::optional getTotalSpace() const override diff --git a/src/Disks/DiskLocal.cpp b/src/Disks/DiskLocal.cpp index 12a5b615234..5363c36e7f8 100644 --- a/src/Disks/DiskLocal.cpp +++ b/src/Disks/DiskLocal.cpp @@ -148,8 +148,7 @@ public: { if (entry->is_directory()) return dir_path / entry->path().filename() / ""; - else - return dir_path / entry->path().filename(); + return dir_path / entry->path().filename(); } String name() const override { return entry->path().filename(); } @@ -211,10 +210,9 @@ std::optional DiskLocal::tryReserve(UInt64 bytes) reserved_bytes += bytes; return {unreserved_space - bytes}; } - else - { - LOG_TRACE(logger, "Could not reserve {} on local disk {}. Not enough unreserved space", ReadableSize(bytes), backQuote(name)); - } + + LOG_TRACE(logger, "Could not reserve {} on local disk {}. Not enough unreserved space", ReadableSize(bytes), backQuote(name)); + return {}; } @@ -310,8 +308,7 @@ DirectoryIteratorPtr DiskLocal::iterateDirectory(const String & path) const fs::path meta_path = fs::path(disk_path) / path; if (!broken && fs::exists(meta_path) && fs::is_directory(meta_path)) return std::make_unique(disk_path, path); - else - return std::make_unique(); + return std::make_unique(); } void DiskLocal::moveFile(const String & from_path, const String & to_path) diff --git a/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp b/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp index 1a9cd2c994c..b24b95af85c 100644 --- a/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp +++ b/src/Disks/IO/AsynchronousBoundedReadBuffer.cpp @@ -293,7 +293,7 @@ off_t AsynchronousBoundedReadBuffer::seek(off_t offset, int whence) return new_pos; } - else if (prefetch_future.valid()) + if (prefetch_future.valid()) { read_from_prefetch = true; diff --git a/src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp b/src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp index 0234f8e1dca..51c6045cb68 100644 --- a/src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp +++ b/src/Disks/IO/CachedOnDiskReadBufferFromFile.cpp @@ -295,12 +295,10 @@ CachedOnDiskReadBufferFromFile::getReadBufferForFileSegment(FileSegment & file_s read_type = ReadType::CACHED; return getCacheReadBuffer(file_segment); } - else - { - LOG_TEST(log, "Bypassing cache because `read_from_filesystem_cache_if_exists_otherwise_bypass_cache` option is used"); - read_type = ReadType::REMOTE_FS_READ_BYPASS_CACHE; - return getRemoteReadBuffer(file_segment, read_type); - } + + LOG_TEST(log, "Bypassing cache because `read_from_filesystem_cache_if_exists_otherwise_bypass_cache` option is used"); + read_type = ReadType::REMOTE_FS_READ_BYPASS_CACHE; + return getRemoteReadBuffer(file_segment, read_type); } while (true) @@ -403,14 +401,13 @@ CachedOnDiskReadBufferFromFile::getReadBufferForFileSegment(FileSegment & file_s read_type = ReadType::CACHED; return getCacheReadBuffer(file_segment); } - else - { - LOG_TRACE( - log, "Bypassing cache because file segment state is " - "`PARTIALLY_DOWNLOADED_NO_CONTINUATION` and downloaded part already used"); - read_type = ReadType::REMOTE_FS_READ_BYPASS_CACHE; - return getRemoteReadBuffer(file_segment, read_type); - } + + LOG_TRACE( + log, + "Bypassing cache because file segment state is " + "`PARTIALLY_DOWNLOADED_NO_CONTINUATION` and downloaded part already used"); + read_type = ReadType::REMOTE_FS_READ_BYPASS_CACHE; + return getRemoteReadBuffer(file_segment, read_type); } } } diff --git a/src/Disks/IO/IOUringReader.cpp b/src/Disks/IO/IOUringReader.cpp index b0e783e11d9..56e08d4e259 100644 --- a/src/Disks/IO/IOUringReader.cpp +++ b/src/Disks/IO/IOUringReader.cpp @@ -121,19 +121,15 @@ std::future IOUringReader::submit(Request request) } return (kv->second).promise.get_future(); } - else - { - ProfileEvents::increment(ProfileEvents::ReadBufferFromFileDescriptorReadFailed); - return makeFailedResult(Exception( - ErrorCodes::IO_URING_SUBMIT_ERROR, "Failed submitting SQE: {}", ret < 0 ? errnoToString(-ret) : "no SQE submitted")); - } - } - else - { - CurrentMetrics::add(CurrentMetrics::IOUringPendingEvents); - pending_requests.push_back(std::move(enqueued_request)); - return pending_requests.back().promise.get_future(); + + ProfileEvents::increment(ProfileEvents::ReadBufferFromFileDescriptorReadFailed); + return makeFailedResult( + Exception(ErrorCodes::IO_URING_SUBMIT_ERROR, "Failed submitting SQE: {}", ret < 0 ? errnoToString(-ret) : "no SQE submitted")); } + + CurrentMetrics::add(CurrentMetrics::IOUringPendingEvents); + pending_requests.push_back(std::move(enqueued_request)); + return pending_requests.back().promise.get_future(); } int IOUringReader::submitToRing(EnqueuedRequest & enqueued) diff --git a/src/Disks/IO/ThreadPoolReader.cpp b/src/Disks/IO/ThreadPoolReader.cpp index da31388a8ea..a7d567930bd 100644 --- a/src/Disks/IO/ThreadPoolReader.cpp +++ b/src/Disks/IO/ThreadPoolReader.cpp @@ -164,29 +164,25 @@ std::future ThreadPoolReader::submit(Request reques has_pread_nowait_support.store(false, std::memory_order_relaxed); break; } - else if (errno == EAGAIN) + if (errno == EAGAIN) { /// Data is not available in page cache. Will hand off to thread pool. break; } - else if (errno == EINTR) + if (errno == EINTR) { /// Interrupted by a signal. continue; } - else - { - ProfileEvents::increment(ProfileEvents::ReadBufferFromFileDescriptorReadFailed); - promise.set_exception(std::make_exception_ptr( - ErrnoException(ErrorCodes::CANNOT_READ_FROM_FILE_DESCRIPTOR, "Cannot read from file {}", fd))); - return future; - } - } - else - { - bytes_read += res; - __msan_unpoison(request.buf, res); + + ProfileEvents::increment(ProfileEvents::ReadBufferFromFileDescriptorReadFailed); + promise.set_exception( + std::make_exception_ptr(ErrnoException(ErrorCodes::CANNOT_READ_FROM_FILE_DESCRIPTOR, "Cannot read from file {}", fd))); + return future; } + + bytes_read += res; + __msan_unpoison(request.buf, res); } if (bytes_read) diff --git a/src/Disks/IO/WriteBufferFromAzureBlobStorage.cpp b/src/Disks/IO/WriteBufferFromAzureBlobStorage.cpp index 5315e331dbd..afc853e3a45 100644 --- a/src/Disks/IO/WriteBufferFromAzureBlobStorage.cpp +++ b/src/Disks/IO/WriteBufferFromAzureBlobStorage.cpp @@ -152,10 +152,8 @@ void WriteBufferFromAzureBlobStorage::preFinalize() detached_part_data.pop_front(); return; } - else - { - writeMultipartUpload(); - } + + writeMultipartUpload(); } void WriteBufferFromAzureBlobStorage::finalizeImpl() diff --git a/src/Disks/ObjectStorages/DiskObjectStorage.cpp b/src/Disks/ObjectStorages/DiskObjectStorage.cpp index 474851df7d5..2330833c70b 100644 --- a/src/Disks/ObjectStorages/DiskObjectStorage.cpp +++ b/src/Disks/ObjectStorages/DiskObjectStorage.cpp @@ -414,10 +414,9 @@ bool DiskObjectStorage::tryReserve(UInt64 bytes) reserved_bytes += bytes; return true; } - else - { - LOG_TRACE(log, "Could not reserve {} on remote disk {}. Not enough unreserved space", ReadableSize(bytes), backQuote(name)); - } + + LOG_TRACE(log, "Could not reserve {} on remote disk {}. Not enough unreserved space", ReadableSize(bytes), backQuote(name)); + return false; } diff --git a/src/Disks/ObjectStorages/MetadataStorageFromPlainRewritableObjectStorage.cpp b/src/Disks/ObjectStorages/MetadataStorageFromPlainRewritableObjectStorage.cpp index 0a133d1042a..ef12615b2d8 100644 --- a/src/Disks/ObjectStorages/MetadataStorageFromPlainRewritableObjectStorage.cpp +++ b/src/Disks/ObjectStorages/MetadataStorageFromPlainRewritableObjectStorage.cpp @@ -232,8 +232,7 @@ bool MetadataStorageFromPlainRewritableObjectStorage::isDirectory(const std::str auto directory = std::filesystem::path(object_storage->generateObjectKeyForPath(path, getMetadataKeyPrefix()).serialize()) / ""; return object_storage->existsOrHasAnyChild(directory); } - else - return MetadataStorageFromPlainObjectStorage::isDirectory(path); + return MetadataStorageFromPlainObjectStorage::isDirectory(path); } std::vector MetadataStorageFromPlainRewritableObjectStorage::listDirectory(const std::string & path) const diff --git a/src/Disks/ObjectStorages/ObjectStorageFactory.cpp b/src/Disks/ObjectStorages/ObjectStorageFactory.cpp index 49a33dbf85b..5cae4936dea 100644 --- a/src/Disks/ObjectStorages/ObjectStorageFactory.cpp +++ b/src/Disks/ObjectStorages/ObjectStorageFactory.cpp @@ -76,7 +76,7 @@ ObjectStoragePtr createObjectStorage( { if (isPlainStorage(type, config, config_prefix)) return std::make_shared>(std::forward(args)...); - else if (isPlainRewritableStorage(type, config, config_prefix)) + if (isPlainRewritableStorage(type, config, config_prefix)) { /// HDFS object storage currently does not support iteration and does not implement listObjects method. /// StaticWeb object storage is read-only and works with its dedicated metadata type. @@ -94,8 +94,7 @@ ObjectStoragePtr createObjectStorage( return std::make_shared>( std::move(metadata_storage_metrics), std::forward(args)...); } - else - return std::make_shared(std::forward(args)...); + return std::make_shared(std::forward(args)...); } } diff --git a/src/Disks/ObjectStorages/StaticDirectoryIterator.h b/src/Disks/ObjectStorages/StaticDirectoryIterator.h index 3e4ad1c3ea9..fe85b3f98b1 100644 --- a/src/Disks/ObjectStorages/StaticDirectoryIterator.h +++ b/src/Disks/ObjectStorages/StaticDirectoryIterator.h @@ -26,8 +26,7 @@ public: { if (iter->filename().empty()) return iter->parent_path().filename(); - else - return iter->filename(); + return iter->filename(); } private: diff --git a/src/Disks/ObjectStorages/Web/WebObjectStorage.cpp b/src/Disks/ObjectStorages/Web/WebObjectStorage.cpp index 61ea584c4ad..32e3c569a67 100644 --- a/src/Disks/ObjectStorages/Web/WebObjectStorage.cpp +++ b/src/Disks/ObjectStorages/Web/WebObjectStorage.cpp @@ -199,38 +199,30 @@ WebObjectStorage::FileDataPtr WebObjectStorage::tryGetFileInfo(const String & pa if (auto jt = files.find(path, is_file); jt != files.end()) return jt->second; - else - { - return nullptr; - } + + return nullptr; } - else + + auto it = std::lower_bound( + files.begin(), files.end(), path, [](const auto & file, const std::string & path_) { return file.first < path_; }); + if (it != files.end()) { - auto it = std::lower_bound( - files.begin(), files.end(), path, - [](const auto & file, const std::string & path_) { return file.first < path_; } - ); - if (it != files.end()) + if (startsWith(it->first, path) || (it != files.begin() && startsWith(std::prev(it)->first, path))) { - if (startsWith(it->first, path) - || (it != files.begin() && startsWith(std::prev(it)->first, path))) - { - shared_lock.unlock(); - std::unique_lock unique_lock(metadata_mutex); + shared_lock.unlock(); + std::unique_lock unique_lock(metadata_mutex); - /// Add this directory path not files cache to simplify further checks for this path. - return files.add(path, FileData::createDirectoryInfo(false)).first->second; - } + /// Add this directory path not files cache to simplify further checks for this path. + return files.add(path, FileData::createDirectoryInfo(false)).first->second; } - - shared_lock.unlock(); - std::unique_lock unique_lock(metadata_mutex); - - if (auto jt = files.find(path, is_file); jt != files.end()) - return jt->second; - else - return loadFiles(path, unique_lock).first; } + + shared_lock.unlock(); + std::unique_lock unique_lock(metadata_mutex); + + if (auto jt = files.find(path, is_file); jt != files.end()) + return jt->second; + return loadFiles(path, unique_lock).first; } std::unique_ptr WebObjectStorage::readObject( /// NOLINT diff --git a/src/Disks/ObjectStorages/Web/WebObjectStorage.h b/src/Disks/ObjectStorages/Web/WebObjectStorage.h index 9b94ae01021..573221b7e21 100644 --- a/src/Disks/ObjectStorages/Web/WebObjectStorage.h +++ b/src/Disks/ObjectStorages/Web/WebObjectStorage.h @@ -124,16 +124,14 @@ protected: { if (is_file) return std::map::find(path); - else - return std::map::find(path.ends_with("/") ? path : path + '/'); + return std::map::find(path.ends_with("/") ? path : path + '/'); } auto add(const String & path, FileDataPtr data) { if (data->type == FileType::Directory) return emplace(path.ends_with("/") ? path : path + '/', data); - else - return emplace(path, data); + return emplace(path, data); } }; diff --git a/src/Disks/StoragePolicy.cpp b/src/Disks/StoragePolicy.cpp index ccdc34d5d06..e2bab00f935 100644 --- a/src/Disks/StoragePolicy.cpp +++ b/src/Disks/StoragePolicy.cpp @@ -327,8 +327,7 @@ VolumePtr StoragePolicy::getVolume(size_t index) const { if (index < volume_index_by_volume_name.size()) return volumes[index]; - else - throw Exception(ErrorCodes::UNKNOWN_VOLUME, "No volume with index {} in storage policy {}", std::to_string(index), backQuote(name)); + throw Exception(ErrorCodes::UNKNOWN_VOLUME, "No volume with index {} in storage policy {}", std::to_string(index), backQuote(name)); } diff --git a/src/Disks/VolumeJBOD.cpp b/src/Disks/VolumeJBOD.cpp index f8b9a57affe..8a9091dff0c 100644 --- a/src/Disks/VolumeJBOD.cpp +++ b/src/Disks/VolumeJBOD.cpp @@ -170,8 +170,7 @@ bool VolumeJBOD::areMergesAvoided() const auto are_merges_avoided_user_override_value = are_merges_avoided_user_override.load(std::memory_order_acquire); if (are_merges_avoided_user_override_value) return *are_merges_avoided_user_override_value; - else - return are_merges_avoided; + return are_merges_avoided; } void VolumeJBOD::setAvoidMergesUserOverride(bool avoid) diff --git a/src/Formats/EscapingRuleUtils.cpp b/src/Formats/EscapingRuleUtils.cpp index 50a46d2334d..67371784712 100644 --- a/src/Formats/EscapingRuleUtils.cpp +++ b/src/Formats/EscapingRuleUtils.cpp @@ -25,22 +25,21 @@ FormatSettings::EscapingRule stringToEscapingRule(const String & escaping_rule) { if (escaping_rule.empty()) return FormatSettings::EscapingRule::None; - else if (escaping_rule == "None") + if (escaping_rule == "None") return FormatSettings::EscapingRule::None; - else if (escaping_rule == "Escaped") + if (escaping_rule == "Escaped") return FormatSettings::EscapingRule::Escaped; - else if (escaping_rule == "Quoted") + if (escaping_rule == "Quoted") return FormatSettings::EscapingRule::Quoted; - else if (escaping_rule == "CSV") + if (escaping_rule == "CSV") return FormatSettings::EscapingRule::CSV; - else if (escaping_rule == "JSON") + if (escaping_rule == "JSON") return FormatSettings::EscapingRule::JSON; - else if (escaping_rule == "XML") + if (escaping_rule == "XML") return FormatSettings::EscapingRule::XML; - else if (escaping_rule == "Raw") + if (escaping_rule == "Raw") return FormatSettings::EscapingRule::Raw; - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown escaping rule \"{}\"", escaping_rule); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown escaping rule \"{}\"", escaping_rule); } String escapingRuleToString(FormatSettings::EscapingRule escaping_rule) diff --git a/src/Formats/FormatSchemaInfo.cpp b/src/Formats/FormatSchemaInfo.cpp index 2509f07ac0a..caa89fb7d0f 100644 --- a/src/Formats/FormatSchemaInfo.cpp +++ b/src/Formats/FormatSchemaInfo.cpp @@ -23,10 +23,9 @@ namespace { if (format == "Protobuf") return "proto"; - else if (format == "CapnProto") + if (format == "CapnProto") return "capnp"; - else - return ""; + return ""; } } @@ -43,20 +42,16 @@ FormatSchemaInfo::FormatSchemaInfo(const String & format_schema, const String & { size_t colon_pos = format_schema.find(':'); if ((colon_pos == String::npos) || (colon_pos == 0) || (colon_pos == format_schema.length() - 1)) - { throw Exception(ErrorCodes::BAD_ARGUMENTS, "Format schema requires the 'format_schema' setting to have the 'schema_file:message_name' format{}. Got '{}'", (default_file_extension.empty() ? "" : ", e.g. 'schema." + default_file_extension + ":Message'"), format_schema); - } - else - { - path = fs::path(format_schema.substr(0, colon_pos)); - String filename = path.has_filename() ? path.filename() : path.parent_path().filename(); - if (filename.empty()) - throw Exception(ErrorCodes::BAD_ARGUMENTS, - "Format schema requires the 'format_schema' setting to have the 'schema_file:message_name' format{}. Got '{}'", - (default_file_extension.empty() ? "" : ", e.g. 'schema." + default_file_extension + ":Message'"), format_schema); - } + path = fs::path(format_schema.substr(0, colon_pos)); + String filename = path.has_filename() ? path.filename() : path.parent_path().filename(); + if (filename.empty()) + throw Exception(ErrorCodes::BAD_ARGUMENTS, + "Format schema requires the 'format_schema' setting to have the 'schema_file:message_name' format{}. Got '{}'", + (default_file_extension.empty() ? "" : ", e.g. 'schema." + default_file_extension + ":Message'"), format_schema); + message_name = format_schema.substr(colon_pos + 1); } else diff --git a/src/Formats/JSONUtils.cpp b/src/Formats/JSONUtils.cpp index 1fc6f02700b..082de35a672 100644 --- a/src/Formats/JSONUtils.cpp +++ b/src/Formats/JSONUtils.cpp @@ -56,7 +56,7 @@ namespace JSONUtils if (pos > in.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (pos == in.buffer().end()) + if (pos == in.buffer().end()) continue; if (*pos == '\\') @@ -77,10 +77,10 @@ namespace JSONUtils if (pos > in.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (pos == in.buffer().end()) + if (pos == in.buffer().end()) continue; - else if (*pos == opening_bracket) + if (*pos == opening_bracket) { ++balance; ++pos; @@ -136,7 +136,7 @@ namespace JSONUtils if (in.position() > in.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (in.position() == in.buffer().end()) + if (in.position() == in.buffer().end()) continue; if (*in.position() == '\\') @@ -158,10 +158,10 @@ namespace JSONUtils if (in.position() > in.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (in.position() == in.buffer().end()) + if (in.position() == in.buffer().end()) continue; - else if (*in.position() == opening_bracket) + if (*in.position() == opening_bracket) { ++balance; ++in.position(); @@ -299,8 +299,7 @@ namespace JSONUtils if (format_settings.json.empty_as_default) return JSONUtils::deserializeEmpyStringAsDefaultOrNested(column, in, deserialize); - else - return deserialize(column, in); + return deserialize(column, in); } catch (Exception & e) { diff --git a/src/Formats/ProtobufSchemas.cpp b/src/Formats/ProtobufSchemas.cpp index 1e355d0484f..8da5b53253a 100644 --- a/src/Formats/ProtobufSchemas.cpp +++ b/src/Formats/ProtobufSchemas.cpp @@ -71,20 +71,18 @@ public: return message_descriptor; } - else - { - const auto * envelope_descriptor = file_descriptor->FindMessageTypeByName("Envelope"); - if (!envelope_descriptor) - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Could not find a message named 'Envelope' in the schema file '{}'", - schema_path); - const auto * message_descriptor = envelope_descriptor->FindNestedTypeByName(message_name); // silly protobuf API disallows a restricting the field type to messages - if (!message_descriptor) - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Could not find a message named '{}' in the schema file '{}'", - message_name, schema_path); + const auto * envelope_descriptor = file_descriptor->FindMessageTypeByName("Envelope"); + if (!envelope_descriptor) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Could not find a message named 'Envelope' in the schema file '{}'", schema_path); - return message_descriptor; - } + const auto * message_descriptor = envelope_descriptor->FindNestedTypeByName( + message_name); // silly protobuf API disallows a restricting the field type to messages + if (!message_descriptor) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, "Could not find a message named '{}' in the schema file '{}'", message_name, schema_path); + + return message_descriptor; } private: diff --git a/src/Formats/ProtobufSerializer.cpp b/src/Formats/ProtobufSerializer.cpp index 20426e8eccb..8aee284f42c 100644 --- a/src/Formats/ProtobufSerializer.cpp +++ b/src/Formats/ProtobufSerializer.cpp @@ -510,8 +510,7 @@ namespace UInt64 u64 = readUInt(); if (u64 < 2) return castNumber(u64); - else - cannotConvertValue(toString(u64), field_descriptor.type_name(), TypeName); + cannotConvertValue(toString(u64), field_descriptor.type_name(), TypeName); }; default_function = [this]() -> NumberType { return static_cast(field_descriptor.default_value_bool()); }; @@ -1323,8 +1322,7 @@ namespace UInt64 u64 = readUInt(); if (u64 < 2) return numberToDecimal(static_cast(u64 != 0)); - else - cannotConvertValue(toString(u64), field_descriptor.type_name(), TypeName); + cannotConvertValue(toString(u64), field_descriptor.type_name(), TypeName); }; default_function = [this]() -> DecimalType @@ -3048,15 +3046,13 @@ namespace #endif return message_serializer; } - else - { - auto envelope_serializer = std::make_unique(std::move(message_serializer), reader_or_writer); - *root_serializer_ptr = envelope_serializer.get(); -#if 0 + + auto envelope_serializer = std::make_unique(std::move(message_serializer), reader_or_writer); + *root_serializer_ptr = envelope_serializer.get(); +# if 0 LOG_INFO(getLogger("ProtobufSerializer"), "Serialization tree:\n{}", get_root_desc_function(0)); -#endif - return envelope_serializer; - } +# endif + return envelope_serializer; } private: @@ -3806,14 +3802,12 @@ namespace max_abs = std::max(std::abs(enum_descriptor->value(i)->number()), max_abs); if (max_abs < 128) return NameAndTypePair{field_descriptor->name(), getEnumDataType(enum_descriptor)}; - else if (max_abs < 32768) + if (max_abs < 32768) return NameAndTypePair{field_descriptor->name(), getEnumDataType(enum_descriptor)}; - else - { - if (skip_unsupported_fields) - return std::nullopt; - throw Exception(ErrorCodes::BAD_ARGUMENTS, "ClickHouse supports only 8-bit and 16-bit enums"); - } + + if (skip_unsupported_fields) + return std::nullopt; + throw Exception(ErrorCodes::BAD_ARGUMENTS, "ClickHouse supports only 8-bit and 16-bit enums"); } case FieldTypeId::TYPE_GROUP: case FieldTypeId::TYPE_MESSAGE: @@ -3825,7 +3819,7 @@ namespace return std::nullopt; throw Exception(ErrorCodes::BAD_ARGUMENTS, "Empty messages are not supported"); } - else if (message_descriptor->field_count() == 1) + if (message_descriptor->field_count() == 1) { const auto * nested_field_descriptor = message_descriptor->field(0); auto nested_name_and_type @@ -3834,24 +3828,23 @@ namespace return std::nullopt; return NameAndTypePair{field_descriptor->name() + "_" + nested_name_and_type->name, nested_name_and_type->type}; } - else - { - DataTypes nested_types; - Strings nested_names; - for (int i = 0; i != message_descriptor->field_count(); ++i) - { - auto nested_name_and_type = getNameAndDataTypeFromFieldRecursive( - message_descriptor->field(i), skip_unsupported_fields, true, pending_resolution); - if (!nested_name_and_type) - continue; - nested_types.push_back(nested_name_and_type->type); - nested_names.push_back(nested_name_and_type->name); - } - if (nested_types.empty()) - return std::nullopt; - return NameAndTypePair{field_descriptor->name(), std::make_shared(std::move(nested_types), std::move(nested_names))}; + DataTypes nested_types; + Strings nested_names; + for (int i = 0; i != message_descriptor->field_count(); ++i) + { + auto nested_name_and_type = getNameAndDataTypeFromFieldRecursive( + message_descriptor->field(i), skip_unsupported_fields, true, pending_resolution); + if (!nested_name_and_type) + continue; + nested_types.push_back(nested_name_and_type->type); + nested_names.push_back(nested_name_and_type->name); } + + if (nested_types.empty()) + return std::nullopt; + return NameAndTypePair{ + field_descriptor->name(), std::make_shared(std::move(nested_types), std::move(nested_names))}; } } diff --git a/src/Formats/SchemaInferenceUtils.cpp b/src/Formats/SchemaInferenceUtils.cpp index ae421a125ea..56a134e8dca 100644 --- a/src/Formats/SchemaInferenceUtils.cpp +++ b/src/Formats/SchemaInferenceUtils.cpp @@ -1349,7 +1349,7 @@ namespace return std::make_shared(); return makeNullable(std::make_shared()); } - else if (checkStringCaseInsensitive("an", buf)) + if (checkStringCaseInsensitive("an", buf)) return std::make_shared(); } diff --git a/src/Functions/CastOverloadResolver.cpp b/src/Functions/CastOverloadResolver.cpp index e6888d9e280..681f43be466 100644 --- a/src/Functions/CastOverloadResolver.cpp +++ b/src/Functions/CastOverloadResolver.cpp @@ -48,8 +48,7 @@ public: return "accurateCastOrNull"; if (internal) return "_CAST"; - else - return "CAST"; + return "CAST"; } String getName() const override @@ -74,15 +73,11 @@ public: static FunctionOverloadResolverPtr create(ContextPtr context, CastType cast_type, bool internal, std::optional diagnostic) { if (internal) - { return std::make_unique(context, cast_type, internal, diagnostic, false /*keep_nullable*/, DataTypeValidationSettings{}); - } - else - { - const auto & settings_ref = context->getSettingsRef(); - return std::make_unique( - context, cast_type, internal, diagnostic, settings_ref[Setting::cast_keep_nullable], DataTypeValidationSettings(settings_ref)); - } + + const auto & settings_ref = context->getSettingsRef(); + return std::make_unique( + context, cast_type, internal, diagnostic, settings_ref[Setting::cast_keep_nullable], DataTypeValidationSettings(settings_ref)); } static FunctionBasePtr createInternalCast(ColumnWithTypeAndName from, DataTypePtr to, CastType cast_type, std::optional diagnostic) diff --git a/src/Functions/DateTimeTransforms.h b/src/Functions/DateTimeTransforms.h index f7075e72b5e..0a3b8fd5d63 100644 --- a/src/Functions/DateTimeTransforms.h +++ b/src/Functions/DateTimeTransforms.h @@ -106,7 +106,7 @@ struct ToDateImpl { if (t < 0) return UInt16(0); - else if (t > DATE_LUT_MAX_DAY_NUM) + if (t > DATE_LUT_MAX_DAY_NUM) return UInt16(DATE_LUT_MAX_DAY_NUM); } else if constexpr (date_time_overflow_behavior == FormatSettings::DateTimeOverflowBehavior::Throw) @@ -702,9 +702,7 @@ struct ToStartOfInterval { if (origin == 0) return time_zone.toStartOfWeekInterval(time_zone.toDayNum(t / scale_multiplier), weeks); - else - return ToStartOfInterval::execute(t, weeks * 7, time_zone, scale_multiplier, origin); - + return ToStartOfInterval::execute(t, weeks * 7, time_zone, scale_multiplier, origin); } }; @@ -728,18 +726,16 @@ struct ToStartOfInterval const Int64 scaled_time = t / scale_multiplier; if (origin == 0) return time_zone.toStartOfMonthInterval(time_zone.toDayNum(scaled_time), months); - else - { - const Int64 scaled_origin = origin / scale_multiplier; - const Int64 days = time_zone.toDayOfMonth(scaled_time + scaled_origin) - time_zone.toDayOfMonth(scaled_origin); - Int64 months_to_add = time_zone.toMonth(scaled_time + scaled_origin) - time_zone.toMonth(scaled_origin); - const Int64 years = time_zone.toYear(scaled_time + scaled_origin) - time_zone.toYear(scaled_origin); - months_to_add = days < 0 ? months_to_add - 1 : months_to_add; - months_to_add += years * 12; - Int64 month_multiplier = (months_to_add / months) * months; - return (time_zone.addMonths(time_zone.toDate(scaled_origin), month_multiplier) - time_zone.toDate(scaled_origin)); - } + const Int64 scaled_origin = origin / scale_multiplier; + const Int64 days = time_zone.toDayOfMonth(scaled_time + scaled_origin) - time_zone.toDayOfMonth(scaled_origin); + Int64 months_to_add = time_zone.toMonth(scaled_time + scaled_origin) - time_zone.toMonth(scaled_origin); + const Int64 years = time_zone.toYear(scaled_time + scaled_origin) - time_zone.toYear(scaled_origin); + months_to_add = days < 0 ? months_to_add - 1 : months_to_add; + months_to_add += years * 12; + Int64 month_multiplier = (months_to_add / months) * months; + + return (time_zone.addMonths(time_zone.toDate(scaled_origin), month_multiplier) - time_zone.toDate(scaled_origin)); } }; @@ -762,8 +758,7 @@ struct ToStartOfInterval { if (origin == 0) return time_zone.toStartOfQuarterInterval(time_zone.toDayNum(t / scale_multiplier), quarters); - else - return ToStartOfInterval::execute(t, quarters * 3, time_zone, scale_multiplier, origin); + return ToStartOfInterval::execute(t, quarters * 3, time_zone, scale_multiplier, origin); } }; @@ -786,8 +781,7 @@ struct ToStartOfInterval { if (origin == 0) return time_zone.toStartOfYearInterval(time_zone.toDayNum(t / scale_multiplier), years); - else - return ToStartOfInterval::execute(t, years * 12, time_zone, scale_multiplier, origin); + return ToStartOfInterval::execute(t, years * 12, time_zone, scale_multiplier, origin); } }; @@ -906,19 +900,18 @@ struct ToStartOfMillisecondImpl { return datetime64; } - else if (scale_multiplier <= 1000) + if (scale_multiplier <= 1000) { return datetime64 * (1000 / scale_multiplier); } - else - { - auto droppable_part_with_sign = DecimalUtils::getFractionalPartWithScaleMultiplier(datetime64, scale_multiplier / 1000); + + auto droppable_part_with_sign + = DecimalUtils::getFractionalPartWithScaleMultiplier(datetime64, scale_multiplier / 1000); if (droppable_part_with_sign < 0) droppable_part_with_sign += scale_multiplier; return datetime64 - droppable_part_with_sign; - } } static UInt32 execute(UInt32, const DateLUTImpl &) @@ -950,19 +943,18 @@ struct ToStartOfMicrosecondImpl { return datetime64; } - else if (scale_multiplier <= 1000000) + if (scale_multiplier <= 1000000) { return datetime64 * (1000000 / scale_multiplier); } - else - { - auto droppable_part_with_sign = DecimalUtils::getFractionalPartWithScaleMultiplier(datetime64, scale_multiplier / 1000000); - if (droppable_part_with_sign < 0) - droppable_part_with_sign += scale_multiplier; + auto droppable_part_with_sign + = DecimalUtils::getFractionalPartWithScaleMultiplier(datetime64, scale_multiplier / 1000000); - return datetime64 - droppable_part_with_sign; - } + if (droppable_part_with_sign < 0) + droppable_part_with_sign += scale_multiplier; + + return datetime64 - droppable_part_with_sign; } static UInt32 execute(UInt32, const DateLUTImpl &) @@ -993,14 +985,12 @@ struct ToStartOfNanosecondImpl { return datetime64; } - else if (scale_multiplier <= 1000000000) + if (scale_multiplier <= 1000000000) { return datetime64 * (1000000000 / scale_multiplier); } - else - { - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type of argument for function {}, DateTime64 expected", name); - } + + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type of argument for function {}, DateTime64 expected", name); } static UInt32 execute(UInt32, const DateLUTImpl &) @@ -1233,10 +1223,11 @@ struct ToYearImpl if (isDateOrDate32(type) || isDateTime(type) || isDateTime64(type)) return {std::make_pair(Field(start_time), Field(end_time))}; - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Illegal type {} of argument of function {}. Should be Date, Date32, DateTime or DateTime64", - type.getName(), name); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal type {} of argument of function {}. Should be Date, Date32, DateTime or DateTime64", + type.getName(), + name); } using FactorTransform = ZeroTransform; @@ -2039,10 +2030,11 @@ struct ToYYYYMMImpl if (isDateOrDate32(type) || isDateTime(type) || isDateTime64(type)) return {std::make_pair(Field(start_time), Field(end_time))}; - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Illegal type {} of argument of function {}. Should be Date, Date32, DateTime or DateTime64", - type.getName(), name); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal type {} of argument of function {}. Should be Date, Date32, DateTime or DateTime64", + type.getName(), + name); } using FactorTransform = ZeroTransform; @@ -2246,12 +2238,12 @@ struct DateTimeTransformImpl return mutable_result_col; } - else - { - throw Exception(ErrorCodes::ILLEGAL_COLUMN, - "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), Transform::name); - } + + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal column {} of first argument of function {}", + arguments[0].column->getName(), + Transform::name); } }; diff --git a/src/Functions/FunctionBase64Conversion.h b/src/Functions/FunctionBase64Conversion.h index 363b9ee3a31..dcee2bc6ea7 100644 --- a/src/Functions/FunctionBase64Conversion.h +++ b/src/Functions/FunctionBase64Conversion.h @@ -212,7 +212,7 @@ public: const auto & input_column = arguments[0].column; if (const auto * src_column_as_fixed_string = checkAndGetColumn(&*input_column)) return execute(*src_column_as_fixed_string, input_rows_count); - else if (const auto * src_column_as_string = checkAndGetColumn(&*input_column)) + if (const auto * src_column_as_string = checkAndGetColumn(&*input_column)) return execute(*src_column_as_string, input_rows_count); throw Exception( diff --git a/src/Functions/FunctionBinaryArithmetic.h b/src/Functions/FunctionBinaryArithmetic.h index ee4e28a7858..df239b820af 100644 --- a/src/Functions/FunctionBinaryArithmetic.h +++ b/src/Functions/FunctionBinaryArithmetic.h @@ -572,7 +572,7 @@ public: scale_a); return; } - else if (scale_b != 1) + if (scale_b != 1) { for (size_t i = 0; i < size; ++i) c[i] = applyScaled( @@ -593,7 +593,7 @@ public: scale_a); return; } - else if (scale_b != 1) + if (scale_b != 1) { for (size_t i = 0; i < size; ++i) c[i] = applyScaled( @@ -602,7 +602,6 @@ public: scale_b); return; } - } else if constexpr (is_division && is_decimal_b) { @@ -1117,8 +1116,7 @@ class FunctionBinaryArithmetic : public IFunction if (agg_state_is_const) return ColumnConst::create(std::move(column_to), input_rows_count); - else - return column_to; + return column_to; } /// Merge two aggregation states together. @@ -1150,8 +1148,7 @@ class FunctionBinaryArithmetic : public IFunction if (lhs_is_const && rhs_is_const) return ColumnConst::create(std::move(column_to), input_rows_count); - else - return column_to; + return column_to; } ColumnPtr executeDateTimeIntervalPlusMinus(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, @@ -1280,7 +1277,7 @@ class FunctionBinaryArithmetic : public IFunction new_arguments[1] = {right_const->convertToFullColumnIfConst(), arguments[1].type, arguments[1].name}; return executeImpl(new_arguments, result_type, input_rows_count); } - else if (left_const && !is_swapped) + if (left_const && !is_swapped) { new_arguments[0] = {left_const->convertToFullColumnIfConst(), arguments[0].type, arguments[0].name}; new_arguments[1] = {arguments[1].column.get()->getPtr(), arguments[1].type, arguments[1].name}; @@ -1984,11 +1981,12 @@ ColumnPtr executeStringInteger(const ColumnsWithTypeAndName & arguments, const A return ColumnConst::create(std::move(col_res), col_left_const->size()); } - else if (!col_left_const && !col_right_const && col_right) + if (!col_left_const && !col_right_const && col_right) { if constexpr (std::is_same_v) { - OpImpl::template processFixedString(in_vec.data(), col_left->getN(), col_right->getData().data(), out_vec, col_left->size()); + OpImpl::template processFixedString( + in_vec.data(), col_left->getN(), col_right->getData().data(), out_vec, col_left->size()); } else { @@ -2018,7 +2016,8 @@ ColumnPtr executeStringInteger(const ColumnsWithTypeAndName & arguments, const A const T1 value = col_right_const->template getValue(); if constexpr (std::is_same_v) { - OpImpl::template processFixedString(in_vec.data(), col_left->getN(), &value, out_vec, col_left->size()); + OpImpl::template processFixedString( + in_vec.data(), col_left->getN(), &value, out_vec, col_left->size()); } else { @@ -2448,16 +2447,14 @@ public: return Base::executeImpl(columns_with_constant, result_type, input_rows_count); } - else if (right.column && isColumnConst(*right.column) && arguments.size() == 1) + if (right.column && isColumnConst(*right.column) && arguments.size() == 1) { ColumnsWithTypeAndName columns_with_constant - = {arguments[0], - {right.column->cloneResized(input_rows_count), right.type, right.name}}; + = {arguments[0], {right.column->cloneResized(input_rows_count), right.type, right.name}}; return Base::executeImpl(columns_with_constant, result_type, input_rows_count); } - else - return Base::executeImpl(arguments, result_type, input_rows_count); + return Base::executeImpl(arguments, result_type, input_rows_count); } bool hasInformationAboutMonotonicity() const override @@ -2526,20 +2523,16 @@ public: // Check if there is an overflow if (is_positive_monotonicity) return {true, true, false, true}; - else - return {false, true, false, false}; - } - else - { - // Check if there is an overflow - if (!is_positive_monotonicity) - return {true, false, false, true}; - else - return {false, false, false, false}; + return {false, true, false, false}; } + + // Check if there is an overflow + if (!is_positive_monotonicity) + return {true, false, false, true}; + return {false, false, false, false}; } // variable +|- constant - else if (right.column && isColumnConst(*right.column)) + if (right.column && isColumnConst(*right.column)) { auto left_type = removeNullable(removeLowCardinality(left.type)); auto right_type = removeNullable(removeLowCardinality(right.type)); @@ -2561,8 +2554,7 @@ public: if (applyVisitor(FieldVisitorAccurateLess(), left_point, right_point) == applyVisitor(FieldVisitorAccurateLess(), transform(left_point), transform(right_point))) return {true, true, false, true}; - else - return {false, true, false, false}; + return {false, true, false, false}; } } if (name_view == "divide" || name_view == "intDiv") @@ -2582,8 +2574,7 @@ public: { return {true, is_constant_positive, false, is_strict}; } - else if ( - applyVisitor(FieldVisitorAccurateLess(), Field(0), left_point) + if (applyVisitor(FieldVisitorAccurateLess(), Field(0), left_point) && applyVisitor(FieldVisitorAccurateLess(), Field(0), right_point)) { return {true, !is_constant_positive, false, is_strict}; diff --git a/src/Functions/FunctionBitTestMany.h b/src/Functions/FunctionBitTestMany.h index 514b78ce59f..b5e66e935ee 100644 --- a/src/Functions/FunctionBitTestMany.h +++ b/src/Functions/FunctionBitTestMany.h @@ -106,7 +106,7 @@ private: return out_col; } - else if (const auto value_col_const = checkAndGetColumnConst>(value_col_untyped)) + if (const auto value_col_const = checkAndGetColumnConst>(value_col_untyped)) { bool is_const; const auto const_mask = createConstMaskIfConst(arguments, is_const); @@ -116,18 +116,16 @@ private: { return result_type->createColumnConst(input_rows_count, toField(Impl::apply(val, const_mask))); } - else - { - const auto mask = createMask(input_rows_count, arguments); - auto out_col = ColumnVector::create(input_rows_count); - auto & out = out_col->getData(); + const auto mask = createMask(input_rows_count, arguments); + auto out_col = ColumnVector::create(input_rows_count); - for (size_t i = 0; i < input_rows_count; ++i) - out[i] = Impl::apply(val, mask[i]); + auto & out = out_col->getData(); - return out_col; - } + for (size_t i = 0; i < input_rows_count; ++i) + out[i] = Impl::apply(val, mask[i]); + + return out_col; } return nullptr; @@ -195,12 +193,14 @@ private: return true; } - else if (const auto pos_col_const = checkAndGetColumnConst>(pos_col_untyped)) + if (const auto pos_col_const = checkAndGetColumnConst>(pos_col_untyped)) { const auto & pos = pos_col_const->template getValue(); if (pos >= 8 * sizeof(ValueType)) - throw Exception(ErrorCodes::PARAMETER_OUT_OF_BOUND, - "The bit position argument {} is out of bounds for number", static_cast(pos)); + throw Exception( + ErrorCodes::PARAMETER_OUT_OF_BOUND, + "The bit position argument {} is out of bounds for number", + static_cast(pos)); const auto new_mask = ValueType(1) << pos; diff --git a/src/Functions/FunctionCustomWeekToDateOrDate32.h b/src/Functions/FunctionCustomWeekToDateOrDate32.h index 2d465d33d7b..a33a476df25 100644 --- a/src/Functions/FunctionCustomWeekToDateOrDate32.h +++ b/src/Functions/FunctionCustomWeekToDateOrDate32.h @@ -39,8 +39,7 @@ public: WhichDataType which(from_type); if ((which.isDate32() || which.isDateTime64()) && enable_extended_results_for_datetime_functions) return std::make_shared(); - else - return std::make_shared(); + return std::make_shared(); } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override @@ -50,31 +49,37 @@ public: if (which.isDate()) return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, Transform{}); - else if (which.isDate32()) + if (which.isDate32()) { if (enable_extended_results_for_datetime_functions) - return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, Transform{}); - else - return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, Transform{}); + return CustomWeekTransformImpl::execute( + arguments, result_type, input_rows_count, Transform{}); + return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, Transform{}); } - else if (which.isDateTime()) - return CustomWeekTransformImpl::execute( - arguments, result_type, input_rows_count, Transform{}); - else if (which.isDateTime64()) + if (which.isDateTime()) + return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, Transform{}); + if (which.isDateTime64()) { if (enable_extended_results_for_datetime_functions) - return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, - TransformDateTime64{assert_cast(from_type)->getScale()}); - else - return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, + return CustomWeekTransformImpl::execute( + arguments, + result_type, + input_rows_count, TransformDateTime64{assert_cast(from_type)->getScale()}); + return CustomWeekTransformImpl::execute( + arguments, + result_type, + input_rows_count, + TransformDateTime64{assert_cast(from_type)->getScale()}); } - else if (Transform::value_may_be_string && which.isString()) - return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, Transform{}); // TODO - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Illegal type {} of argument of function {}", - arguments[0].type->getName(), this->getName()); + if (Transform::value_may_be_string && which.isString()) + return CustomWeekTransformImpl::execute( + arguments, result_type, input_rows_count, Transform{}); // TODO + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal type {} of argument of function {}", + arguments[0].type->getName(), + this->getName()); } }; diff --git a/src/Functions/FunctionCustomWeekToSomething.h b/src/Functions/FunctionCustomWeekToSomething.h index a631a0118cb..96669dd3be7 100644 --- a/src/Functions/FunctionCustomWeekToSomething.h +++ b/src/Functions/FunctionCustomWeekToSomething.h @@ -30,19 +30,23 @@ public: if (which.isDate()) return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, Transform{}); - else if (which.isDate32()) + if (which.isDate32()) return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, Transform{}); - else if (which.isDateTime()) + if (which.isDateTime()) return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, Transform{}); - else if (which.isDateTime64()) - return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, + if (which.isDateTime64()) + return CustomWeekTransformImpl::execute( + arguments, + result_type, + input_rows_count, TransformDateTime64{assert_cast(from_type)->getScale()}); - else if (Transform::value_may_be_string && which.isString()) + if (Transform::value_may_be_string && which.isString()) return CustomWeekTransformImpl::execute(arguments, result_type, input_rows_count, Transform{}); - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Illegal type {} of argument of function {}", - arguments[0].type->getName(), this->getName()); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal type {} of argument of function {}", + arguments[0].type->getName(), + this->getName()); } }; diff --git a/src/Functions/FunctionDateOrDateTimeAddInterval.h b/src/Functions/FunctionDateOrDateTimeAddInterval.h index 25231b8887b..68c18a9e985 100644 --- a/src/Functions/FunctionDateOrDateTimeAddInterval.h +++ b/src/Functions/FunctionDateOrDateTimeAddInterval.h @@ -708,20 +708,27 @@ public: if (which.isDate()) return DateTimeAddIntervalImpl, Transform>::execute(Transform{}, arguments, result_type, 0, input_rows_count); - else if (which.isDate32()) - return DateTimeAddIntervalImpl, Transform>::execute(Transform{}, arguments, result_type, 0, input_rows_count); - else if (which.isDateTime()) - return DateTimeAddIntervalImpl, Transform>::execute(Transform{}, arguments, result_type, 0, input_rows_count); - else if (which.isDateTime64()) + if (which.isDate32()) + return DateTimeAddIntervalImpl, Transform>::execute( + Transform{}, arguments, result_type, 0, input_rows_count); + if (which.isDateTime()) + return DateTimeAddIntervalImpl, Transform>::execute( + Transform{}, arguments, result_type, 0, input_rows_count); + if (which.isDateTime64()) { const auto * datetime64_type = assert_cast(from_type); auto from_scale = datetime64_type->getScale(); - return DateTimeAddIntervalImpl, Transform>::execute(Transform{}, arguments, result_type, from_scale, input_rows_count); + return DateTimeAddIntervalImpl, Transform>::execute( + Transform{}, arguments, result_type, from_scale, input_rows_count); } - else if (which.isString()) - return DateTimeAddIntervalImpl::execute(Transform{}, arguments, result_type, 3, input_rows_count); - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of first argument of function {}", arguments[0].type->getName(), getName()); + if (which.isString()) + return DateTimeAddIntervalImpl::execute( + Transform{}, arguments, result_type, 3, input_rows_count); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal type {} of first argument of function {}", + arguments[0].type->getName(), + getName()); } }; diff --git a/src/Functions/FunctionDateOrDateTimeToDateOrDate32.h b/src/Functions/FunctionDateOrDateTimeToDateOrDate32.h index c1a2c9c08f5..404a8e8eccf 100644 --- a/src/Functions/FunctionDateOrDateTimeToDateOrDate32.h +++ b/src/Functions/FunctionDateOrDateTimeToDateOrDate32.h @@ -48,8 +48,7 @@ public: if ((which.isDate32() || which.isDateTime64()) && enable_extended_results_for_datetime_functions) return std::make_shared(); - else - return std::make_shared(); + return std::make_shared(); } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override @@ -59,29 +58,31 @@ public: if (which.isDate()) return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); - else if (which.isDate32()) + if (which.isDate32()) { if (enable_extended_results_for_datetime_functions) - return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); - else - return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); + return DateTimeTransformImpl::execute( + arguments, result_type, input_rows_count); + return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); } - else if (which.isDateTime()) + if (which.isDateTime()) return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); - else if (which.isDateTime64()) + if (which.isDateTime64()) { const auto scale = static_cast(from_type)->getScale(); const TransformDateTime64 transformer(scale); if (enable_extended_results_for_datetime_functions) - return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count, transformer); - else - return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count, transformer); + return DateTimeTransformImpl:: + execute(arguments, result_type, input_rows_count, transformer); + return DateTimeTransformImpl::execute( + arguments, result_type, input_rows_count, transformer); } - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Illegal type {} of argument of function {}", - arguments[0].type->getName(), this->getName()); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal type {} of argument of function {}", + arguments[0].type->getName(), + this->getName()); } }; diff --git a/src/Functions/FunctionDateOrDateTimeToDateTimeOrDateTime64.h b/src/Functions/FunctionDateOrDateTimeToDateTimeOrDateTime64.h index bde4bbfa322..08153d6a7f4 100644 --- a/src/Functions/FunctionDateOrDateTimeToDateTimeOrDateTime64.h +++ b/src/Functions/FunctionDateOrDateTimeToDateTimeOrDateTime64.h @@ -59,8 +59,7 @@ public: } return std::make_shared(scale, time_zone); } - else - return std::make_shared(time_zone); + return std::make_shared(time_zone); } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override @@ -69,29 +68,31 @@ public: WhichDataType which(from_type); if (which.isDate()) return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); - else if (which.isDate32()) + if (which.isDate32()) { if (enable_extended_results_for_datetime_functions) - return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); - else - return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); + return DateTimeTransformImpl::execute( + arguments, result_type, input_rows_count); + return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); } - else if (which.isDateTime()) + if (which.isDateTime()) return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); - else if (which.isDateTime64()) + if (which.isDateTime64()) { const auto scale = static_cast(from_type)->getScale(); const TransformDateTime64 transformer(scale); if (enable_extended_results_for_datetime_functions) - return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count, transformer); - else - return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count, transformer); + return DateTimeTransformImpl:: + execute(arguments, result_type, input_rows_count, transformer); + return DateTimeTransformImpl::execute( + arguments, result_type, input_rows_count, transformer); } - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Illegal type {} of argument of function {}", - arguments[0].type->getName(), this->getName()); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal type {} of argument of function {}", + arguments[0].type->getName(), + this->getName()); } }; diff --git a/src/Functions/FunctionDateOrDateTimeToSomething.h b/src/Functions/FunctionDateOrDateTimeToSomething.h index 166e5e7ca9b..f7c058ff18d 100644 --- a/src/Functions/FunctionDateOrDateTimeToSomething.h +++ b/src/Functions/FunctionDateOrDateTimeToSomething.h @@ -62,20 +62,22 @@ public: if (isDate(from_type)) return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); - else if (isDate32(from_type)) + if (isDate32(from_type)) return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); - else if (isDateTime(from_type)) + if (isDateTime(from_type)) return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count); - else if (isDateTime64(from_type)) + if (isDateTime64(from_type)) { const auto scale = static_cast(from_type)->getScale(); const TransformDateTime64 transformer(scale); - return DateTimeTransformImpl::execute(arguments, result_type, input_rows_count, transformer); + return DateTimeTransformImpl::execute( + arguments, result_type, input_rows_count, transformer); } - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Illegal type {} of argument of function {}", - arguments[0].type->getName(), this->getName()); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal type {} of argument of function {}", + arguments[0].type->getName(), + this->getName()); } bool hasInformationAboutPreimage() const override { return Transform::hasPreimage(); } diff --git a/src/Functions/FunctionFactory.cpp b/src/Functions/FunctionFactory.cpp index 70af9f881da..cd5d9d2c877 100644 --- a/src/Functions/FunctionFactory.cpp +++ b/src/Functions/FunctionFactory.cpp @@ -81,8 +81,7 @@ FunctionOverloadResolverPtr FunctionFactory::getImpl( auto hints = this->getHints(name); if (!hints.empty()) throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "Unknown function {}{}. Maybe you meant: {}", name, extra_info, toString(hints)); - else - throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "Unknown function {}{}", name, extra_info); + throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "Unknown function {}{}", name, extra_info); } return res; diff --git a/src/Functions/FunctionHelpers.cpp b/src/Functions/FunctionHelpers.cpp index c658063b66f..9f8fbd4cb52 100644 --- a/src/Functions/FunctionHelpers.cpp +++ b/src/Functions/FunctionHelpers.cpp @@ -59,12 +59,12 @@ ColumnWithTypeAndName columnGetNested(const ColumnWithTypeAndName & col) { return ColumnWithTypeAndName{nullptr, nested_type, col.name}; } - else if (const auto * nullable = checkAndGetColumn(&*col.column)) + if (const auto * nullable = checkAndGetColumn(&*col.column)) { const auto & nested_col = nullable->getNestedColumnPtr(); return ColumnWithTypeAndName{nested_col, nested_type, col.name}; } - else if (const auto * const_column = checkAndGetColumn(&*col.column)) + if (const auto * const_column = checkAndGetColumn(&*col.column)) { const auto * nullable_column = checkAndGetColumn(&const_column->getDataColumn()); @@ -78,10 +78,9 @@ ColumnWithTypeAndName columnGetNested(const ColumnWithTypeAndName & col) { nullable_res = makeNullable(col.column); } - return ColumnWithTypeAndName{ nullable_res, nested_type, col.name }; + return ColumnWithTypeAndName{nullable_res, nested_type, col.name}; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} for DataTypeNullable", col.dumpStructure()); + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} for DataTypeNullable", col.dumpStructure()); } return col; } @@ -214,7 +213,7 @@ ColumnPtr wrapInNullable(const ColumnPtr & src, const ColumnsWithTypeAndName & a if (src->onlyNull()) return src; - else if (const auto * nullable = checkAndGetColumn(&*src)) + if (const auto * nullable = checkAndGetColumn(&*src)) { src_not_nullable = nullable->getNestedColumnPtr(); result_null_map_column = nullable->getNullMapColumnPtr(); diff --git a/src/Functions/FunctionMathUnary.h b/src/Functions/FunctionMathUnary.h index 3cc8bf391b4..7838d764e5e 100644 --- a/src/Functions/FunctionMathUnary.h +++ b/src/Functions/FunctionMathUnary.h @@ -54,8 +54,7 @@ private: /// Integers are converted to Float64. if (Impl::always_returns_float64 || !isFloat(argument)) return std::make_shared(); - else - return argument; + return argument; } template diff --git a/src/Functions/FunctionSQLJSON.h b/src/Functions/FunctionSQLJSON.h index 47fdf5eba27..d56e655e126 100644 --- a/src/Functions/FunctionSQLJSON.h +++ b/src/Functions/FunctionSQLJSON.h @@ -334,10 +334,8 @@ public: DataTypePtr string_type = std::make_shared(); return std::make_shared(string_type); } - else - { - return std::make_shared(); - } + + return std::make_shared(); } static size_t getNumberOfIndexArguments(const ColumnsWithTypeAndName & arguments) { return arguments.size() - 1; } @@ -355,7 +353,7 @@ public: { break; } - else if (!(current_element.isArray() || current_element.isObject())) + if (!(current_element.isArray() || current_element.isObject())) { break; } diff --git a/src/Functions/FunctionStringOrArrayToT.h b/src/Functions/FunctionStringOrArrayToT.h index cd98e0f5875..c5a3b037676 100644 --- a/src/Functions/FunctionStringOrArrayToT.h +++ b/src/Functions/FunctionStringOrArrayToT.h @@ -76,7 +76,7 @@ public: return col_res; } - else if (const ColumnFixedString * col_fixed = checkAndGetColumn(column.get())) + if (const ColumnFixedString * col_fixed = checkAndGetColumn(column.get())) { if (Impl::is_fixed_to_constant) { @@ -85,18 +85,16 @@ public: return result_type->createColumnConst(col_fixed->size(), toField(res)); } - else - { - auto col_res = ColumnVector::create(); - typename ColumnVector::Container & vec_res = col_res->getData(); - vec_res.resize(col_fixed->size()); - Impl::vectorFixedToVector(col_fixed->getChars(), col_fixed->getN(), vec_res, input_rows_count); + auto col_res = ColumnVector::create(); - return col_res; - } + typename ColumnVector::Container & vec_res = col_res->getData(); + vec_res.resize(col_fixed->size()); + Impl::vectorFixedToVector(col_fixed->getChars(), col_fixed->getN(), vec_res, input_rows_count); + + return col_res; } - else if (const ColumnArray * col_arr = checkAndGetColumn(column.get())) + if (const ColumnArray * col_arr = checkAndGetColumn(column.get())) { auto col_res = ColumnVector::create(); @@ -106,7 +104,7 @@ public: return col_res; } - else if (const ColumnMap * col_map = checkAndGetColumn(column.get())) + if (const ColumnMap * col_map = checkAndGetColumn(column.get())) { auto col_res = ColumnVector::create(); typename ColumnVector::Container & vec_res = col_res->getData(); @@ -116,7 +114,7 @@ public: Impl::array(col_nested.getOffsets(), vec_res, input_rows_count); return col_res; } - else if (const ColumnUUID * col_uuid = checkAndGetColumn(column.get())) + if (const ColumnUUID * col_uuid = checkAndGetColumn(column.get())) { auto col_res = ColumnVector::create(); typename ColumnVector::Container & vec_res = col_res->getData(); @@ -124,7 +122,7 @@ public: Impl::uuid(col_uuid->getData(), input_rows_count, vec_res, input_rows_count); return col_res; } - else if (const ColumnIPv6 * col_ipv6 = checkAndGetColumn(column.get())) + if (const ColumnIPv6 * col_ipv6 = checkAndGetColumn(column.get())) { auto col_res = ColumnVector::create(); typename ColumnVector::Container & vec_res = col_res->getData(); @@ -132,7 +130,7 @@ public: Impl::ipv6(col_ipv6->getData(), input_rows_count, vec_res, input_rows_count); return col_res; } - else if (const ColumnIPv4 * col_ipv4 = checkAndGetColumn(column.get())) + if (const ColumnIPv4 * col_ipv4 = checkAndGetColumn(column.get())) { auto col_res = ColumnVector::create(); typename ColumnVector::Container & vec_res = col_res->getData(); @@ -140,9 +138,8 @@ public: Impl::ipv4(col_ipv4->getData(), input_rows_count, vec_res, input_rows_count); return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/FunctionStringReplace.h b/src/Functions/FunctionStringReplace.h index 432e03bfe9e..a7b6e1ccd86 100644 --- a/src/Functions/FunctionStringReplace.h +++ b/src/Functions/FunctionStringReplace.h @@ -74,51 +74,60 @@ public: input_rows_count); return col_res; } - else if (col_haystack && col_needle_vector && col_replacement_const) + if (col_haystack && col_needle_vector && col_replacement_const) { Impl::vectorVectorConstant( - col_haystack->getChars(), col_haystack->getOffsets(), - col_needle_vector->getChars(), col_needle_vector->getOffsets(), + col_haystack->getChars(), + col_haystack->getOffsets(), + col_needle_vector->getChars(), + col_needle_vector->getOffsets(), col_replacement_const->getValue(), - col_res->getChars(), col_res->getOffsets(), + col_res->getChars(), + col_res->getOffsets(), input_rows_count); return col_res; } - else if (col_haystack && col_needle_const && col_replacement_vector) + if (col_haystack && col_needle_const && col_replacement_vector) { Impl::vectorConstantVector( - col_haystack->getChars(), col_haystack->getOffsets(), + col_haystack->getChars(), + col_haystack->getOffsets(), col_needle_const->getValue(), - col_replacement_vector->getChars(), col_replacement_vector->getOffsets(), - col_res->getChars(), col_res->getOffsets(), + col_replacement_vector->getChars(), + col_replacement_vector->getOffsets(), + col_res->getChars(), + col_res->getOffsets(), input_rows_count); return col_res; } - else if (col_haystack && col_needle_vector && col_replacement_vector) + if (col_haystack && col_needle_vector && col_replacement_vector) { Impl::vectorVectorVector( - col_haystack->getChars(), col_haystack->getOffsets(), - col_needle_vector->getChars(), col_needle_vector->getOffsets(), - col_replacement_vector->getChars(), col_replacement_vector->getOffsets(), - col_res->getChars(), col_res->getOffsets(), + col_haystack->getChars(), + col_haystack->getOffsets(), + col_needle_vector->getChars(), + col_needle_vector->getOffsets(), + col_replacement_vector->getChars(), + col_replacement_vector->getOffsets(), + col_res->getChars(), + col_res->getOffsets(), input_rows_count); return col_res; } - else if (col_haystack_fixed && col_needle_const && col_replacement_const) + if (col_haystack_fixed && col_needle_const && col_replacement_const) { Impl::vectorFixedConstantConstant( - col_haystack_fixed->getChars(), col_haystack_fixed->getN(), + col_haystack_fixed->getChars(), + col_haystack_fixed->getN(), col_needle_const->getValue(), col_replacement_const->getValue(), - col_res->getChars(), col_res->getOffsets(), + col_res->getChars(), + col_res->getOffsets(), input_rows_count); return col_res; } - else - throw Exception( - ErrorCodes::ILLEGAL_COLUMN, - "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/FunctionStringToString.h b/src/Functions/FunctionStringToString.h index e0e64e47b49..4c1483d1f03 100644 --- a/src/Functions/FunctionStringToString.h +++ b/src/Functions/FunctionStringToString.h @@ -68,15 +68,14 @@ public: Impl::vector(col->getChars(), col->getOffsets(), col_res->getChars(), col_res->getOffsets(), input_rows_count); return col_res; } - else if (const ColumnFixedString * col_fixed = checkAndGetColumn(column.get())) + if (const ColumnFixedString * col_fixed = checkAndGetColumn(column.get())) { auto col_res = ColumnFixedString::create(col_fixed->getN()); Impl::vectorFixed(col_fixed->getChars(), col_fixed->getN(), col_res->getChars(), input_rows_count); return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/FunctionTokens.h b/src/Functions/FunctionTokens.h index ceb2669056f..38e76c8f867 100644 --- a/src/Functions/FunctionTokens.h +++ b/src/Functions/FunctionTokens.h @@ -148,7 +148,7 @@ public: return col_res; } - else if (col_str_const) + if (col_str_const) { String src = col_str_const->getValue(); Array dst; @@ -162,9 +162,12 @@ public: return result_type->createColumnConst(col_str_const->size(), dst); } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal columns {}, {} of arguments of function {}", - array_argument.column->getName(), array_argument.column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal columns {}, {} of arguments of function {}", + array_argument.column->getName(), + array_argument.column->getName(), + getName()); } }; diff --git a/src/Functions/FunctionsAES.h b/src/Functions/FunctionsAES.h index 7af6265eba9..4f8e94291d6 100644 --- a/src/Functions/FunctionsAES.h +++ b/src/Functions/FunctionsAES.h @@ -241,10 +241,9 @@ private: { return doEncryptImpl(evp_cipher, input_rows_count, input_column, key_column, iv_column, aad_column); } - else - { - return doEncryptImpl(evp_cipher, input_rows_count, input_column, key_column, iv_column, aad_column); - } + + return doEncryptImpl( + evp_cipher, input_rows_count, input_column, key_column, iv_column, aad_column); } return nullptr; @@ -517,10 +516,9 @@ private: { return doDecryptImpl(evp_cipher, input_rows_count, input_column, key_column, iv_column, aad_column); } - else - { - return doDecryptImpl(evp_cipher, input_rows_count, input_column, key_column, iv_column, aad_column); - } + + return doDecryptImpl( + evp_cipher, input_rows_count, input_column, key_column, iv_column, aad_column); } return nullptr; diff --git a/src/Functions/FunctionsBinaryRepresentation.cpp b/src/Functions/FunctionsBinaryRepresentation.cpp index b3861f0394d..a2b1d38d516 100644 --- a/src/Functions/FunctionsBinaryRepresentation.cpp +++ b/src/Functions/FunctionsBinaryRepresentation.cpp @@ -344,10 +344,8 @@ public: col_res = std::move(col_str); return true; } - else - { - return false; - } + + return false; } bool tryExecuteString(const IColumn *col, ColumnPtr &col_res) const @@ -389,10 +387,8 @@ public: col_res = std::move(col_str); return true; } - else - { - return false; - } + + return false; } template @@ -405,10 +401,8 @@ public: Impl::executeFloatAndDecimal(in_vec, col_res, sizeof(T)); return true; } - else - { - return false; - } + + return false; } static bool tryExecuteFixedString(const IColumn * col, ColumnPtr & col_res) @@ -451,10 +445,8 @@ public: col_res = std::move(col_str); return true; } - else - { - return false; - } + + return false; } template @@ -467,10 +459,8 @@ public: Impl::executeFloatAndDecimal(in_vec, col_res, sizeof(T)); return true; } - else - { - return false; - } + + return false; } bool tryExecuteUUID(const IColumn * col, ColumnPtr & col_res) const @@ -515,10 +505,8 @@ public: col_res = std::move(col_str); return true; } - else - { - return false; - } + + return false; } bool tryExecuteIPv6(const IColumn * col, ColumnPtr & col_res) const @@ -680,7 +668,7 @@ public: return col_res; } - else if (const ColumnFixedString * col_fix_string = checkAndGetColumn(column.get())) + if (const ColumnFixedString * col_fix_string = checkAndGetColumn(column.get())) { auto col_res = ColumnString::create(); @@ -691,7 +679,8 @@ public: const size_t n = col_fix_string->getN(); out_offsets.resize(input_rows_count); - out_vec.resize(((n + word_size - 1) / word_size + /* trailing zero symbol that is always added by Impl::decode */ 1) * input_rows_count); + out_vec.resize( + ((n + word_size - 1) / word_size + /* trailing zero symbol that is always added by Impl::decode */ 1) * input_rows_count); char * begin = reinterpret_cast(out_vec.data()); char * pos = begin; @@ -702,7 +691,8 @@ public: size_t new_offset = prev_offset + n; /// here we don't subtract 1 from `new_offset` because in ColumnFixedString strings are stored without trailing zero byte - Impl::decode(reinterpret_cast(&in_vec[prev_offset]), reinterpret_cast(&in_vec[new_offset]), pos); + Impl::decode( + reinterpret_cast(&in_vec[prev_offset]), reinterpret_cast(&in_vec[new_offset]), pos); out_offsets[i] = pos - begin; @@ -716,11 +706,9 @@ public: return col_res; } - else - { - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); - } + + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/FunctionsBitToArray.cpp b/src/Functions/FunctionsBitToArray.cpp index 0a14516268a..8004be667bd 100644 --- a/src/Functions/FunctionsBitToArray.cpp +++ b/src/Functions/FunctionsBitToArray.cpp @@ -188,10 +188,8 @@ public: out_column = ColumnArray::create(std::move(col_values), std::move(col_offsets)); return true; } - else - { - return false; - } + + return false; } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t /*input_rows_count*/) const override diff --git a/src/Functions/FunctionsBitmap.h b/src/Functions/FunctionsBitmap.h index 12b2b1a662a..cb1a49fc1ca 100644 --- a/src/Functions/FunctionsBitmap.h +++ b/src/Functions/FunctionsBitmap.h @@ -166,23 +166,22 @@ public: WhichDataType which(nested_type); if (which.isUInt8()) return executeBitmapData(argument_types, arguments, input_rows_count); - else if (which.isUInt16()) + if (which.isUInt16()) return executeBitmapData(argument_types, arguments, input_rows_count); - else if (which.isUInt32()) + if (which.isUInt32()) return executeBitmapData(argument_types, arguments, input_rows_count); - else if (which.isUInt64()) + if (which.isUInt64()) return executeBitmapData(argument_types, arguments, input_rows_count); - else if (which.isInt8()) + if (which.isInt8()) return executeBitmapData(argument_types, arguments, input_rows_count); - else if (which.isInt16()) + if (which.isInt16()) return executeBitmapData(argument_types, arguments, input_rows_count); - else if (which.isInt32()) + if (which.isInt32()) return executeBitmapData(argument_types, arguments, input_rows_count); - else if (which.isInt64()) + if (which.isInt64()) return executeBitmapData(argument_types, arguments, input_rows_count); - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Unexpected type {} of argument of function {}", - from_type->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Unexpected type {} of argument of function {}", from_type->getName(), getName()); } private: @@ -359,23 +358,22 @@ public: WhichDataType which(aggr_type->getArgumentsDataTypes()[0]); if (which.isUInt8()) return executeIntType(arguments, input_rows_count); - else if (which.isUInt16()) + if (which.isUInt16()) return executeIntType(arguments, input_rows_count); - else if (which.isUInt32()) + if (which.isUInt32()) return executeIntType(arguments, input_rows_count); - else if (which.isUInt64()) + if (which.isUInt64()) return executeIntType(arguments, input_rows_count); - else if (which.isInt8()) + if (which.isInt8()) return executeIntType(arguments, input_rows_count); - else if (which.isInt16()) + if (which.isInt16()) return executeIntType(arguments, input_rows_count); - else if (which.isInt32()) + if (which.isInt32()) return executeIntType(arguments, input_rows_count); - else if (which.isInt64()) + if (which.isInt64()) return executeIntType(arguments, input_rows_count); - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Unexpected type {} of argument of function {}", - from_type->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Unexpected type {} of argument of function {}", from_type->getName(), getName()); } private: @@ -538,23 +536,22 @@ public: WhichDataType which(aggr_type->getArgumentsDataTypes()[0]); if (which.isUInt8()) return executeIntType(arguments, input_rows_count); - else if (which.isUInt16()) + if (which.isUInt16()) return executeIntType(arguments, input_rows_count); - else if (which.isUInt32()) + if (which.isUInt32()) return executeIntType(arguments, input_rows_count); - else if (which.isUInt64()) + if (which.isUInt64()) return executeIntType(arguments, input_rows_count); - else if (which.isInt8()) + if (which.isInt8()) return executeIntType(arguments, input_rows_count); - else if (which.isInt16()) + if (which.isInt16()) return executeIntType(arguments, input_rows_count); - else if (which.isInt32()) + if (which.isInt32()) return executeIntType(arguments, input_rows_count); - else if (which.isInt64()) + if (which.isInt64()) return executeIntType(arguments, input_rows_count); - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Unexpected type {} of argument of function {}", - from_type->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Unexpected type {} of argument of function {}", from_type->getName(), getName()); } private: @@ -1136,23 +1133,22 @@ public: WhichDataType which(aggr_type->getArgumentsDataTypes()[0]); if (which.isUInt8()) return executeBitmapData(arguments, input_rows_count); - else if (which.isUInt16()) + if (which.isUInt16()) return executeBitmapData(arguments, input_rows_count); - else if (which.isUInt32()) + if (which.isUInt32()) return executeBitmapData(arguments, input_rows_count); - else if (which.isUInt64()) + if (which.isUInt64()) return executeBitmapData(arguments, input_rows_count); - else if (which.isInt8()) + if (which.isInt8()) return executeBitmapData(arguments, input_rows_count); - else if (which.isInt16()) + if (which.isInt16()) return executeBitmapData(arguments, input_rows_count); - else if (which.isInt32()) + if (which.isInt32()) return executeBitmapData(arguments, input_rows_count); - else if (which.isInt64()) + if (which.isInt64()) return executeBitmapData(arguments, input_rows_count); - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Unexpected type {} of argument of function {}", - from_type->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Unexpected type {} of argument of function {}", from_type->getName(), getName()); } private: diff --git a/src/Functions/FunctionsCodingIP.cpp b/src/Functions/FunctionsCodingIP.cpp index 8c7828a0830..fefa93d890b 100644 --- a/src/Functions/FunctionsCodingIP.cpp +++ b/src/Functions/FunctionsCodingIP.cpp @@ -375,9 +375,8 @@ private: return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } public: static constexpr auto name = Name::name; @@ -661,9 +660,8 @@ public: return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; @@ -776,9 +774,8 @@ public: return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/FunctionsCodingIP.h b/src/Functions/FunctionsCodingIP.h index 9d090abb736..add3562d79d 100644 --- a/src/Functions/FunctionsCodingIP.h +++ b/src/Functions/FunctionsCodingIP.h @@ -219,14 +219,12 @@ ColumnPtr convertToIPv6(ColumnPtr column, const PaddedPODArray * null_map { return detail::convertToIPv6(*column_input_string, null_map); } - else if (const auto * column_input_fixed_string = checkAndGetColumn(column.get())) + if (const auto * column_input_fixed_string = checkAndGetColumn(column.get())) { return detail::convertToIPv6(*column_input_fixed_string, null_map); } - else - { - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column type {}. Expected String or FixedString", column->getName()); - } + + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column type {}. Expected String or FixedString", column->getName()); } template diff --git a/src/Functions/FunctionsCodingUUID.cpp b/src/Functions/FunctionsCodingUUID.cpp index 179ba1bf97a..99d7e0278cb 100644 --- a/src/Functions/FunctionsCodingUUID.cpp +++ b/src/Functions/FunctionsCodingUUID.cpp @@ -40,7 +40,7 @@ std::pair determineBinaryStartIndexWithIncrement(ptrdiff_t num_bytes, { if (representation == Representation::BigEndian) return {0, 1}; - else if (representation == Representation::LittleEndian) + if (representation == Representation::LittleEndian) return {num_bytes - 1, -1}; throw DB::Exception(DB::ErrorCodes::LOGICAL_ERROR, "{} is not handled yet", magic_enum::enum_name(representation)); @@ -214,9 +214,8 @@ public: return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; @@ -291,12 +290,16 @@ public: return col_res; } - else if (const auto * col_in_fixed = checkAndGetColumn(column.get())) + if (const auto * col_in_fixed = checkAndGetColumn(column.get())) { if (col_in_fixed->getN() != uuid_text_length) - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Illegal type {} of column {} argument of function {}, expected FixedString({})", - col_type_name.type->getName(), col_in_fixed->getName(), getName(), uuid_text_length); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal type {} of column {} argument of function {}, expected FixedString({})", + col_type_name.type->getName(), + col_in_fixed->getName(), + getName(), + uuid_text_length); const auto & vec_in = col_in_fixed->getChars(); @@ -317,9 +320,8 @@ public: return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; @@ -393,9 +395,8 @@ public: return col_res; } - else - throw Exception( - ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; @@ -467,9 +468,8 @@ public: return col_res; } - else - throw Exception( - ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/FunctionsComparison.h b/src/Functions/FunctionsComparison.h index 4bee19ba87a..d84f6fe84ac 100644 --- a/src/Functions/FunctionsComparison.h +++ b/src/Functions/FunctionsComparison.h @@ -664,7 +664,7 @@ private: return col_res; } - else if (auto col_right_const = checkAndGetColumnConst>(col_right_untyped)) + if (auto col_right_const = checkAndGetColumnConst>(col_right_untyped)) { auto col_res = ColumnUInt8::create(); @@ -691,10 +691,11 @@ private: return col_res; } - else if (auto col_right_const = checkAndGetColumnConst>(col_right_untyped)) + if (auto col_right_const = checkAndGetColumnConst>(col_right_untyped)) { UInt8 res = 0; - NumComparisonImpl>::constantConstant(col_left->template getValue(), col_right_const->template getValue(), res); + NumComparisonImpl>::constantConstant( + col_left->template getValue(), col_right_const->template getValue(), res); return DataTypeUInt8().createColumnConst(col_left->size(), toField(res)); } @@ -723,13 +724,12 @@ private: || (res = executeNumRightType(col_left, col_right_untyped)) || (res = executeNumRightType(col_left, col_right_untyped))) return res; - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of second argument of function {}", - col_right_untyped->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of second argument of function {}", col_right_untyped->getName(), getName()); } - else if (auto col_left_const = checkAndGetColumnConst>(col_left_untyped)) + if (auto col_left_const = checkAndGetColumnConst>(col_left_untyped)) { - if ( (res = executeNumConstRightType(col_left_const, col_right_untyped)) + if ((res = executeNumConstRightType(col_left_const, col_right_untyped)) || (res = executeNumConstRightType(col_left_const, col_right_untyped)) || (res = executeNumConstRightType(col_left_const, col_right_untyped)) || (res = executeNumConstRightType(col_left_const, col_right_untyped)) @@ -744,9 +744,8 @@ private: || (res = executeNumConstRightType(col_left_const, col_right_untyped)) || (res = executeNumConstRightType(col_left_const, col_right_untyped))) return res; - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of second argument of function {}", - col_right_untyped->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of second argument of function {}", col_right_untyped->getName(), getName()); } return nullptr; @@ -766,8 +765,7 @@ private: if (check_decimal_overflow) return (res = DecimalComparison::apply(col_left, col_right)) != nullptr; - else - return (res = DecimalComparison::apply(col_left, col_right)) != nullptr; + return (res = DecimalComparison::apply(col_left, col_right)) != nullptr; }; if (!callOnBasicTypes(left_number, right_number, call)) @@ -843,58 +841,48 @@ private: return ColumnConst::create(res, c0_const->size()); } + + auto c_res = ColumnUInt8::create(); + ColumnUInt8::Container & vec_res = c_res->getData(); + vec_res.resize(c0->size()); + + if (c0_string && c1_string) + StringImpl::string_vector_string_vector( + c0_string->getChars(), c0_string->getOffsets(), c1_string->getChars(), c1_string->getOffsets(), c_res->getData()); + else if (c0_string && c1_fixed_string) + StringImpl::string_vector_fixed_string_vector( + c0_string->getChars(), c0_string->getOffsets(), c1_fixed_string->getChars(), c1_fixed_string->getN(), c_res->getData()); + else if (c0_string && c1_const) + StringImpl::string_vector_constant( + c0_string->getChars(), c0_string->getOffsets(), *c1_const_chars, c1_const_size, c_res->getData()); + else if (c0_fixed_string && c1_string) + StringImpl::fixed_string_vector_string_vector( + c0_fixed_string->getChars(), c0_fixed_string->getN(), c1_string->getChars(), c1_string->getOffsets(), c_res->getData()); + else if (c0_fixed_string && c1_fixed_string) + StringImpl::fixed_string_vector_fixed_string_vector( + c0_fixed_string->getChars(), + c0_fixed_string->getN(), + c1_fixed_string->getChars(), + c1_fixed_string->getN(), + c_res->getData()); + else if (c0_fixed_string && c1_const) + StringImpl::fixed_string_vector_constant( + c0_fixed_string->getChars(), c0_fixed_string->getN(), *c1_const_chars, c1_const_size, c_res->getData()); + else if (c0_const && c1_string) + StringImpl::constant_string_vector( + *c0_const_chars, c0_const_size, c1_string->getChars(), c1_string->getOffsets(), c_res->getData()); + else if (c0_const && c1_fixed_string) + StringImpl::constant_fixed_string_vector( + *c0_const_chars, c0_const_size, c1_fixed_string->getChars(), c1_fixed_string->getN(), c_res->getData()); else - { - auto c_res = ColumnUInt8::create(); - ColumnUInt8::Container & vec_res = c_res->getData(); - vec_res.resize(c0->size()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal columns {} and {} of arguments of function {}", + c0->getName(), + c1->getName(), + getName()); - if (c0_string && c1_string) - StringImpl::string_vector_string_vector( - c0_string->getChars(), c0_string->getOffsets(), - c1_string->getChars(), c1_string->getOffsets(), - c_res->getData()); - else if (c0_string && c1_fixed_string) - StringImpl::string_vector_fixed_string_vector( - c0_string->getChars(), c0_string->getOffsets(), - c1_fixed_string->getChars(), c1_fixed_string->getN(), - c_res->getData()); - else if (c0_string && c1_const) - StringImpl::string_vector_constant( - c0_string->getChars(), c0_string->getOffsets(), - *c1_const_chars, c1_const_size, - c_res->getData()); - else if (c0_fixed_string && c1_string) - StringImpl::fixed_string_vector_string_vector( - c0_fixed_string->getChars(), c0_fixed_string->getN(), - c1_string->getChars(), c1_string->getOffsets(), - c_res->getData()); - else if (c0_fixed_string && c1_fixed_string) - StringImpl::fixed_string_vector_fixed_string_vector( - c0_fixed_string->getChars(), c0_fixed_string->getN(), - c1_fixed_string->getChars(), c1_fixed_string->getN(), - c_res->getData()); - else if (c0_fixed_string && c1_const) - StringImpl::fixed_string_vector_constant( - c0_fixed_string->getChars(), c0_fixed_string->getN(), - *c1_const_chars, c1_const_size, - c_res->getData()); - else if (c0_const && c1_string) - StringImpl::constant_string_vector( - *c0_const_chars, c0_const_size, - c1_string->getChars(), c1_string->getOffsets(), - c_res->getData()); - else if (c0_const && c1_fixed_string) - StringImpl::constant_fixed_string_vector( - *c0_const_chars, c0_const_size, - c1_fixed_string->getChars(), c1_fixed_string->getN(), - c_res->getData()); - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal columns {} and {} of arguments of function {}", - c0->getName(), c1->getName(), getName()); - - return c_res; - } + return c_res; } ColumnPtr executeWithConstString( @@ -922,18 +910,15 @@ private: { return DataTypeUInt8().createColumnConst(input_rows_count, IsOperation::not_equals); } - else - { - auto column_converted = type_to_compare->createColumnConst(input_rows_count, converted); - ColumnsWithTypeAndName tmp_columns - { - { left_const ? column_converted : col_left_untyped->getPtr(), type_to_compare, "" }, - { !left_const ? column_converted : col_right_untyped->getPtr(), type_to_compare, "" }, - }; + auto column_converted = type_to_compare->createColumnConst(input_rows_count, converted); - return executeImpl(tmp_columns, result_type, input_rows_count); - } + ColumnsWithTypeAndName tmp_columns{ + {left_const ? column_converted : col_left_untyped->getPtr(), type_to_compare, ""}, + {!left_const ? column_converted : col_right_untyped->getPtr(), type_to_compare, ""}, + }; + + return executeImpl(tmp_columns, result_type, input_rows_count); } ColumnPtr executeTuple( @@ -1122,21 +1107,19 @@ private: GenericComparisonImpl>::constantConstant(*c0, *c1, res); return DataTypeUInt8().createColumnConst(c0->size(), toField(res)); } + + auto c_res = ColumnUInt8::create(); + ColumnUInt8::Container & vec_res = c_res->getData(); + vec_res.resize(c0->size()); + + if (c0_const) + GenericComparisonImpl>::constantVector(*c0, *c1, vec_res); + else if (c1_const) + GenericComparisonImpl>::vectorConstant(*c0, *c1, vec_res); else - { - auto c_res = ColumnUInt8::create(); - ColumnUInt8::Container & vec_res = c_res->getData(); - vec_res.resize(c0->size()); + GenericComparisonImpl>::vectorVector(*c0, *c1, vec_res); - if (c0_const) - GenericComparisonImpl>::constantVector(*c0, *c1, vec_res); - else if (c1_const) - GenericComparisonImpl>::vectorConstant(*c0, *c1, vec_res); - else - GenericComparisonImpl>::vectorVector(*c0, *c1, vec_res); - - return c_res; - } + return c_res; } ColumnPtr executeGeneric(const ColumnWithTypeAndName & c0, const ColumnWithTypeAndName & c1) const @@ -1308,37 +1291,31 @@ public: return res; } - else if (checkAndGetDataType(left_type.get()) - && checkAndGetDataType(right_type.get())) + if (checkAndGetDataType(left_type.get()) && checkAndGetDataType(right_type.get())) { return executeTuple(result_type, col_with_type_and_name_left, col_with_type_and_name_right, input_rows_count); } - else if (left_is_string && right_is_string && (res = executeString(col_left_untyped, col_right_untyped))) + if (left_is_string && right_is_string && (res = executeString(col_left_untyped, col_right_untyped))) { return res; } - else if ((res = executeWithConstString( - result_type, col_left_untyped, col_right_untyped, - left_type, right_type, - input_rows_count))) + if ((res = executeWithConstString(result_type, col_left_untyped, col_right_untyped, left_type, right_type, input_rows_count))) { return res; } - else if ( - (((left_is_ipv6 && right_is_fixed_string) || (right_is_ipv6 && left_is_fixed_string)) && fixed_string_size == IPV6_BINARY_LENGTH) - || ((left_is_ipv4 || left_is_ipv6) && (right_is_ipv4 || right_is_ipv6)) - ) + if ((((left_is_ipv6 && right_is_fixed_string) || (right_is_ipv6 && left_is_fixed_string)) + && fixed_string_size == IPV6_BINARY_LENGTH) + || ((left_is_ipv4 || left_is_ipv6) && (right_is_ipv4 || right_is_ipv6))) { /// Special treatment for FixedString(16) as a binary representation of IPv6 & for comparing IPv4 & IPv6 values - /// CAST is customized for this cases - ColumnPtr left_column = left_is_ipv6 ? - col_with_type_and_name_left.column : castColumn(col_with_type_and_name_left, right_type); - ColumnPtr right_column = right_is_ipv6 ? - col_with_type_and_name_right.column : castColumn(col_with_type_and_name_right, left_type); + ColumnPtr left_column = left_is_ipv6 ? col_with_type_and_name_left.column : castColumn(col_with_type_and_name_left, right_type); + ColumnPtr right_column + = right_is_ipv6 ? col_with_type_and_name_right.column : castColumn(col_with_type_and_name_right, left_type); return executeGenericIdenticalTypes(left_column.get(), right_column.get()); } - else if ((isColumnedAsDecimal(left_type) || isColumnedAsDecimal(right_type))) + if ((isColumnedAsDecimal(left_type) || isColumnedAsDecimal(right_type))) { // Comparing Date/Date32 and DateTime64 requires implicit conversion, if (date_and_datetime && (isDateOrDate32(left_type) || isDateOrDate32(right_type))) @@ -1348,29 +1325,30 @@ public: ColumnPtr c1_converted = castColumn(col_with_type_and_name_right, common_type); return executeDecimal({c0_converted, common_type, "left"}, {c1_converted, common_type, "right"}); } - else + + /// Check does another data type is comparable to Decimal, includes Int and Float. + if (!allowDecimalComparison(left_type, right_type) && !date_and_datetime) + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "No operation {} between {} and {}", + getName(), + left_type->getName(), + right_type->getName()); + /// When Decimal comparing to Float32/64, we convert both of them into Float64. + /// Other systems like MySQL and Spark also do as this. + if (left_is_float || right_is_float) { - /// Check does another data type is comparable to Decimal, includes Int and Float. - if (!allowDecimalComparison(left_type, right_type) && !date_and_datetime) - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "No operation {} between {} and {}", - getName(), left_type->getName(), right_type->getName()); - /// When Decimal comparing to Float32/64, we convert both of them into Float64. - /// Other systems like MySQL and Spark also do as this. - if (left_is_float || right_is_float) - { - const auto converted_type = std::make_shared(); - ColumnPtr c0_converted = castColumn(col_with_type_and_name_left, converted_type); - ColumnPtr c1_converted = castColumn(col_with_type_and_name_right, converted_type); + const auto converted_type = std::make_shared(); + ColumnPtr c0_converted = castColumn(col_with_type_and_name_left, converted_type); + ColumnPtr c1_converted = castColumn(col_with_type_and_name_right, converted_type); - auto new_arguments - = ColumnsWithTypeAndName{{c0_converted, converted_type, "left"}, {c1_converted, converted_type, "right"}}; - return executeImpl(new_arguments, result_type, input_rows_count); - } - return executeDecimal(col_with_type_and_name_left, col_with_type_and_name_right); + auto new_arguments + = ColumnsWithTypeAndName{{c0_converted, converted_type, "left"}, {c1_converted, converted_type, "right"}}; + return executeImpl(new_arguments, result_type, input_rows_count); } - + return executeDecimal(col_with_type_and_name_left, col_with_type_and_name_right); } - else if (date_and_datetime) + if (date_and_datetime) { DataTypePtr common_type = getLeastSupertype(DataTypes{left_type, right_type}); ColumnPtr c0_converted = castColumn(col_with_type_and_name_left, common_type); @@ -1382,14 +1360,12 @@ public: throw Exception(ErrorCodes::LOGICAL_ERROR, "Date related common types can only be UInt32/UInt64/Int32/Decimal"); return res; } - else if (types_equal) + if (types_equal) { return executeGenericIdenticalTypes(col_left_untyped, col_right_untyped); } - else - { - return executeGeneric(col_with_type_and_name_left, col_with_type_and_name_right); - } + + return executeGeneric(col_with_type_and_name_left, col_with_type_and_name_right); } }; diff --git a/src/Functions/FunctionsConsistentHashing.h b/src/Functions/FunctionsConsistentHashing.h index 210bb69e16d..8adfca89e40 100644 --- a/src/Functions/FunctionsConsistentHashing.h +++ b/src/Functions/FunctionsConsistentHashing.h @@ -72,9 +72,7 @@ public: { if (isColumnConst(*arguments[1].column)) return executeConstBuckets(arguments); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "The second argument of function {} (number of buckets) must be constant", - getName()); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "The second argument of function {} (number of buckets) must be constant", getName()); } private: diff --git a/src/Functions/FunctionsDecimalArithmetics.h b/src/Functions/FunctionsDecimalArithmetics.h index 9b9045f7c69..c1349e3d6fc 100644 --- a/src/Functions/FunctionsDecimalArithmetics.h +++ b/src/Functions/FunctionsDecimalArithmetics.h @@ -310,12 +310,15 @@ private: using DividendType = DataTypeDecimal32; if (which_divisor.isDecimal32()) return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal64()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal128()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal256()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); + if (which_divisor.isDecimal64()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); + if (which_divisor.isDecimal128()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); + if (which_divisor.isDecimal256()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); } else if (which_dividend.isDecimal64()) @@ -323,13 +326,15 @@ private: using DividendType = DataTypeDecimal64; if (which_divisor.isDecimal32()) return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal64()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal128()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal256()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - + if (which_divisor.isDecimal64()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); + if (which_divisor.isDecimal128()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); + if (which_divisor.isDecimal256()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); } else if (which_dividend.isDecimal128()) @@ -337,13 +342,15 @@ private: using DividendType = DataTypeDecimal128; if (which_divisor.isDecimal32()) return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal64()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal128()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal256()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - + if (which_divisor.isDecimal64()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); + if (which_divisor.isDecimal128()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); + if (which_divisor.isDecimal256()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); } else if (which_dividend.isDecimal256()) @@ -351,13 +358,15 @@ private: using DividendType = DataTypeDecimal256; if (which_divisor.isDecimal32()) return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal64()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal128()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - else if (which_divisor.isDecimal256()) - return DecimalArithmeticsImpl::execute(Transform{}, arguments, result_type, input_rows_count); - + if (which_divisor.isDecimal64()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); + if (which_divisor.isDecimal128()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); + if (which_divisor.isDecimal256()) + return DecimalArithmeticsImpl::execute( + Transform{}, arguments, result_type, input_rows_count); } // the compiler is happy now diff --git a/src/Functions/FunctionsEmbeddedDictionaries.h b/src/Functions/FunctionsEmbeddedDictionaries.h index f27934ce5a9..6ac3bf10e90 100644 --- a/src/Functions/FunctionsEmbeddedDictionaries.h +++ b/src/Functions/FunctionsEmbeddedDictionaries.h @@ -123,8 +123,7 @@ struct IdentityDictionaryGetter { if (key.empty()) return src; - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Dictionary doesn't support 'point of view' keys."); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Dictionary doesn't support 'point of view' keys."); } }; @@ -212,9 +211,8 @@ public: return col_to; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), name); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", arguments[0].column->getName(), name); } }; @@ -309,7 +307,7 @@ public: return col_to; } - else if (col_vec1 && col_const2) + if (col_vec1 && col_const2) { auto col_to = ColumnUInt8::create(); @@ -323,7 +321,7 @@ public: return col_to; } - else if (col_const1 && col_vec2) + if (col_const1 && col_vec2) { auto col_to = ColumnUInt8::create(); @@ -337,14 +335,18 @@ public: return col_to; } - else if (col_const1 && col_const2) + if (col_const1 && col_const2) { - return DataTypeUInt8().createColumnConst(col_const1->size(), + return DataTypeUInt8().createColumnConst( + col_const1->size(), toField(Transform::apply(col_const1->template getValue(), col_const2->template getValue(), dict))); } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal columns {} and {} of arguments of function {}", - arguments[0].column->getName(), arguments[1].column->getName(), name); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal columns {} and {} of arguments of function {}", + arguments[0].column->getName(), + arguments[1].column->getName(), + name); } }; @@ -444,9 +446,8 @@ public: return ColumnArray::create(std::move(col_values), std::move(col_offsets)); } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), name); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", arguments[0].column->getName(), name); } }; @@ -634,9 +635,11 @@ public: return col_to; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of the first argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal column {} of the first argument of function {}", + arguments[0].column->getName(), + getName()); } }; diff --git a/src/Functions/FunctionsExternalDictionaries.h b/src/Functions/FunctionsExternalDictionaries.h index 0b5b52db81a..4c7e1534ba5 100644 --- a/src/Functions/FunctionsExternalDictionaries.h +++ b/src/Functions/FunctionsExternalDictionaries.h @@ -273,11 +273,9 @@ public: getName(), key_column_type->getName()); } - else - { - key_columns = {key_column}; - key_types = {key_column_type}; - } + + key_columns = {key_column}; + key_types = {key_column_type}; } } @@ -402,13 +400,10 @@ public: return std::make_shared(attribute_types, attribute_names); } - else - { - if (key_is_nullable) - return makeNullable(attribute_types.front()); - else - return attribute_types.front(); - } + + if (key_is_nullable) + return makeNullable(attribute_types.front()); + return attribute_types.front(); } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override @@ -574,11 +569,9 @@ public: getName(), key_col_with_type.type->getName()); } - else - { - key_columns = {std::move(key_column)}; - key_types = {std::move(key_column_type)}; - } + + key_columns = {std::move(key_column)}; + key_types = {std::move(key_column_type)}; } } diff --git a/src/Functions/FunctionsHashing.h b/src/Functions/FunctionsHashing.h index 3da0b2cd9be..ce6b0447e63 100644 --- a/src/Functions/FunctionsHashing.h +++ b/src/Functions/FunctionsHashing.h @@ -739,9 +739,9 @@ private: return col_to; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), Name::name); + + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", + arguments[0].column->getName(), Name::name); } public: @@ -772,35 +772,35 @@ public: if (which.isUInt8()) return executeType(arguments); - else if (which.isUInt16()) + if (which.isUInt16()) return executeType(arguments); - else if (which.isUInt32()) + if (which.isUInt32()) return executeType(arguments); - else if (which.isUInt64()) + if (which.isUInt64()) return executeType(arguments); - else if (which.isInt8()) + if (which.isInt8()) return executeType(arguments); - else if (which.isInt16()) + if (which.isInt16()) return executeType(arguments); - else if (which.isInt32()) + if (which.isInt32()) return executeType(arguments); - else if (which.isInt64()) + if (which.isInt64()) return executeType(arguments); - else if (which.isDate()) + if (which.isDate()) return executeType(arguments); - else if (which.isDate32()) + if (which.isDate32()) return executeType(arguments); - else if (which.isDateTime()) + if (which.isDateTime()) return executeType(arguments); - else if (which.isDecimal32()) + if (which.isDecimal32()) return executeType(arguments); - else if (which.isDecimal64()) + if (which.isDecimal64()) return executeType(arguments); - else if (which.isIPv4()) + if (which.isIPv4()) return executeType(arguments); - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of argument of function {}", - arguments[0].type->getName(), getName()); + + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of argument of function {}", + arguments[0].type->getName(), getName()); } }; @@ -1434,8 +1434,7 @@ struct URLHierarchyHashImpl { return 0 == level ? end - begin : 0; } - else - pos += 3; + pos += 3; /// The domain for simplicity is everything that after the protocol and the two slashes, until the next slash or before `?` or `#` while (pos < end && !(*pos == '/' || *pos == '?' || *pos == '#')) @@ -1516,10 +1515,9 @@ public: if (arg_count == 1) return executeSingleArg(arguments); - else if (arg_count == 2) + if (arg_count == 2) return executeTwoArgs(arguments); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "got into IFunction::execute with unexpected number of arguments"); + throw Exception(ErrorCodes::LOGICAL_ERROR, "got into IFunction::execute with unexpected number of arguments"); } private: @@ -1548,9 +1546,8 @@ private: return col_to; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } ColumnPtr executeTwoArgs(const ColumnsWithTypeAndName & arguments) const @@ -1580,7 +1577,7 @@ private: return col_to; } - else if (const auto * col_const_from = checkAndGetColumnConstData(col_untyped)) + if (const auto * col_const_from = checkAndGetColumnConstData(col_untyped)) { auto col_to = ColumnUInt64::create(size); auto & out = col_to->getData(); @@ -1590,17 +1587,13 @@ private: for (size_t i = 0; i < size; ++i) { - out[i] = URLHierarchyHashImpl::apply( - level_col->getUInt(i), - reinterpret_cast(chars.data()), - offsets[0] - 1); + out[i] = URLHierarchyHashImpl::apply(level_col->getUInt(i), reinterpret_cast(chars.data()), offsets[0] - 1); } return col_to; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/FunctionsLogical.cpp b/src/Functions/FunctionsLogical.cpp index ff0cff09c9e..f83a958bf31 100644 --- a/src/Functions/FunctionsLogical.cpp +++ b/src/Functions/FunctionsLogical.cpp @@ -658,8 +658,7 @@ ColumnPtr FunctionAnyArityLogical::executeImpl( if (result_type->isNullable()) return executeForTernaryLogicImpl(std::move(args_in), result_type, input_rows_count); - else - return basicExecuteImpl(std::move(args_in), input_rows_count); + return basicExecuteImpl(std::move(args_in), input_rows_count); } template diff --git a/src/Functions/FunctionsStringDistance.cpp b/src/Functions/FunctionsStringDistance.cpp index 5aae92a8141..4f3383bb1e5 100644 --- a/src/Functions/FunctionsStringDistance.cpp +++ b/src/Functions/FunctionsStringDistance.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #ifdef __SSE4_2__ @@ -284,7 +285,7 @@ struct ByteEditDistanceImpl if (*(needle + pos_needle) != *(haystack + pos_haystack)) substitution += 1; } - distances1[pos_haystack + 1] = std::min(deletion, std::min(substitution, insertion)); + distances1[pos_haystack + 1] = std::min({deletion, substitution, insertion}); } distances0.swap(distances1); } @@ -343,10 +344,11 @@ struct ByteDamerauLevenshteinDistanceImpl for (size_t j = 1; j <= needle_size; ++j) { int cost = (haystack[i - 1] == needle[j - 1]) ? 0 : 1; - starts[i][j] = std::min(starts[i - 1][j] + 1, /// deletion - std::min(starts[i][j - 1] + 1, /// insertion - starts[i - 1][j - 1] + cost) /// substitution - ); + starts[i][j] = std::min( + {starts[i - 1][j] + 1, /// deletion + starts[i][j - 1] + 1, /// insertion + starts[i - 1][j - 1] + cost} /// substitution + ); if (i > 1 && j > 1 && haystack[i - 1] == needle[j - 2] && haystack[i - 2] == needle[j - 1]) starts[i][j] = std::min(starts[i][j], starts[i - 2][j - 2] + 1); /// transposition } @@ -456,7 +458,7 @@ struct ByteJaroWinklerSimilarityImpl if (jaro_winkler_similarity > boost_threshold) { - const int common_length = std::min(max_prefix_length, std::min(s1len, s2len)); + const int common_length = std::min({max_prefix_length, s1len, s2len}); int common_prefix = 0; while (common_prefix < common_length && haystack[common_prefix] == needle[common_prefix]) common_prefix++; diff --git a/src/Functions/FunctionsStringHashFixedString.cpp b/src/Functions/FunctionsStringHashFixedString.cpp index d8f3a3f7c09..fe3fa65b63a 100644 --- a/src/Functions/FunctionsStringHashFixedString.cpp +++ b/src/Functions/FunctionsStringHashFixedString.cpp @@ -266,7 +266,7 @@ public: return col_to; } - else if (const ColumnFixedString * col_from_fix = checkAndGetColumn(arguments[0].column.get())) + if (const ColumnFixedString * col_from_fix = checkAndGetColumn(arguments[0].column.get())) { auto col_to = ColumnFixedString::create(Impl::length); const typename ColumnFixedString::Chars & data = col_from_fix->getChars(); @@ -280,7 +280,7 @@ public: } return col_to; } - else if (const ColumnIPv6 * col_from_ip = checkAndGetColumn(arguments[0].column.get())) + if (const ColumnIPv6 * col_from_ip = checkAndGetColumn(arguments[0].column.get())) { auto col_to = ColumnFixedString::create(Impl::length); const typename ColumnIPv6::Container & data = col_from_ip->getData(); @@ -293,12 +293,8 @@ public: } return col_to; } - else - throw Exception( - ErrorCodes::ILLEGAL_COLUMN, - "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), - getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/FunctionsStringSearch.h b/src/Functions/FunctionsStringSearch.h index 66b85c543cc..d2a5a1b7745 100644 --- a/src/Functions/FunctionsStringSearch.h +++ b/src/Functions/FunctionsStringSearch.h @@ -221,8 +221,7 @@ public: if (is_col_start_pos_const) return result_type->createColumnConst(col_haystack_const->size(), toField(vec_res[0])); - else - return col_res; + return col_res; } } diff --git a/src/Functions/FunctionsStringSearchToString.h b/src/Functions/FunctionsStringSearchToString.h index c889cf062a3..dacb6fa2de7 100644 --- a/src/Functions/FunctionsStringSearchToString.h +++ b/src/Functions/FunctionsStringSearchToString.h @@ -79,9 +79,8 @@ public: return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/FunctionsTimeWindow.cpp b/src/Functions/FunctionsTimeWindow.cpp index 88b85c48326..87614b823d5 100644 --- a/src/Functions/FunctionsTimeWindow.cpp +++ b/src/Functions/FunctionsTimeWindow.cpp @@ -60,11 +60,12 @@ ColumnPtr executeWindowBound(const ColumnPtr & column, size_t index, const Strin "Must be a Tuple(DataTime, DataTime)", function_name); return col_tuple->getColumnPtr(index); } - else - { - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal column for first argument of function {}. " - "Must be Tuple", function_name); - } + + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal column for first argument of function {}. " + "Must be Tuple", + function_name); } void checkFirstArgument(const ColumnWithTypeAndName & argument, const String & function_name) @@ -273,18 +274,16 @@ struct TimeWindowImpl throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Tuple passed to {} should not be empty", function_name); return tuple_elems[0]; } - else if (type.isUInt32()) + if (type.isUInt32()) return std::make_shared(); - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, - "Illegal type of first argument of function {} should be DateTime, Tuple or UInt32", - function_name); - } - else - { - return std::static_pointer_cast(TimeWindowImpl::getReturnType(arguments, function_name)) - ->getElement(0); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal type of first argument of function {} should be DateTime, Tuple or UInt32", + function_name); } + + return std::static_pointer_cast(TimeWindowImpl::getReturnType(arguments, function_name)) + ->getElement(0); } [[maybe_unused]] static ColumnPtr dispatchForColumns(const ColumnsWithTypeAndName & arguments, const String & function_name, size_t input_rows_count) @@ -296,8 +295,8 @@ struct TimeWindowImpl { if (which_type.isUInt32()) return time_column.column; - else //isTuple - result_column = time_column.column; + //isTuple + result_column = time_column.column; } else result_column = TimeWindowImpl::dispatchForColumns(arguments, function_name, input_rows_count); @@ -324,8 +323,8 @@ struct TimeWindowImpl { if (which_type.isUInt32()) return time_column.column; - else //isTuple - result_column = time_column.column; + //isTuple + result_column = time_column.column; } else result_column = TimeWindowImpl::dispatchForColumns(arguments, function_name, input_rows_count); @@ -508,8 +507,7 @@ struct TimeWindowImpl if (result_type_is_date) return std::make_shared(); - else - return std::make_shared(); + return std::make_shared(); } static ColumnPtr dispatchForHopColumns(const ColumnsWithTypeAndName & arguments, const String & function_name, size_t input_rows_count) @@ -605,14 +603,11 @@ struct TimeWindowImpl { if (arguments.size() == 2) return dispatchForTumbleColumns(arguments, function_name, input_rows_count); - else - { - const auto & third_column = arguments[2]; - if (arguments.size() == 3 && WhichDataType(third_column.type).isString()) - return dispatchForTumbleColumns(arguments, function_name, input_rows_count); - else - return dispatchForHopColumns(arguments, function_name, input_rows_count); - } + + const auto & third_column = arguments[2]; + if (arguments.size() == 3 && WhichDataType(third_column.type).isString()) + return dispatchForTumbleColumns(arguments, function_name, input_rows_count); + return dispatchForHopColumns(arguments, function_name, input_rows_count); } }; @@ -633,17 +628,15 @@ struct TimeWindowImpl throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Tuple passed to {} should not be empty", function_name); return tuple_elems[0]; } - else if (type.isUInt32()) + if (type.isUInt32()) return std::make_shared(); - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, - "Illegal type of first argument of function {} should be DateTime, Tuple or UInt32", - function_name); - } - else - { - return std::static_pointer_cast(TimeWindowImpl::getReturnType(arguments, function_name))->getElement(0); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal type of first argument of function {} should be DateTime, Tuple or UInt32", + function_name); } + + return std::static_pointer_cast(TimeWindowImpl::getReturnType(arguments, function_name))->getElement(0); } static ColumnPtr dispatchForColumns(const ColumnsWithTypeAndName & arguments, const String & function_name, size_t input_rows_count) @@ -655,8 +648,8 @@ struct TimeWindowImpl { if (which_type.isUInt32()) return time_column.column; - else //isTuple - result_column = time_column.column; + //isTuple + result_column = time_column.column; } else result_column = TimeWindowImpl::dispatchForColumns(arguments, function_name, input_rows_count); @@ -683,8 +676,8 @@ struct TimeWindowImpl { if (which_type.isUInt32()) return time_column.column; - else //isTuple - result_column = time_column.column; + //isTuple + result_column = time_column.column; } else result_column = TimeWindowImpl::dispatchForColumns(arguments, function_name, input_rows_count); diff --git a/src/Functions/FunctionsTimeWindow.h b/src/Functions/FunctionsTimeWindow.h index 7522bd374a2..0824a02fed0 100644 --- a/src/Functions/FunctionsTimeWindow.h +++ b/src/Functions/FunctionsTimeWindow.h @@ -76,13 +76,9 @@ template<> \ auto val = t * DecimalUtils::scaleMultiplier((DEF_SCALE) - scale); \ if (delta == 1) \ return val; \ - else \ - return val - (val % delta); \ - } \ - else \ - { \ - return t - (t % (delta * DecimalUtils::scaleMultiplier(scale - (DEF_SCALE)))) ; \ + return val - (val % delta); \ } \ + return t - (t % (delta * DecimalUtils::scaleMultiplier(scale - (DEF_SCALE)))) ; \ } \ }; TRANSFORM_SUBSECONDS(Millisecond, 3) @@ -136,11 +132,8 @@ template <> \ static NO_SANITIZE_UNDEFINED Int64 execute(Int64 t, UInt64 delta, const UInt32 scale) \ { \ if (scale < (DEF_SCALE)) \ - { \ return t + delta * DecimalUtils::scaleMultiplier((DEF_SCALE) - scale); \ - } \ - else \ - return t + delta * DecimalUtils::scaleMultiplier(scale - (DEF_SCALE)); \ + return t + delta * DecimalUtils::scaleMultiplier(scale - (DEF_SCALE)); \ } \ }; ADD_SUBSECONDS(Millisecond, 3) diff --git a/src/Functions/FunctionsTonalityClassification.cpp b/src/Functions/FunctionsTonalityClassification.cpp index 7627c68c057..0c1af00462e 100644 --- a/src/Functions/FunctionsTonalityClassification.cpp +++ b/src/Functions/FunctionsTonalityClassification.cpp @@ -56,8 +56,7 @@ struct FunctionDetectTonalityImpl /// Convert values -12..6 to -1..1 if (weight > 0) return static_cast(weight / count_words / 6); - else - return static_cast(weight / count_words / 12); + return static_cast(weight / count_words / 12); } static void vector( diff --git a/src/Functions/GregorianDate.cpp b/src/Functions/GregorianDate.cpp index 82c81d2bb4f..f92c77bf455 100644 --- a/src/Functions/GregorianDate.cpp +++ b/src/Functions/GregorianDate.cpp @@ -54,10 +54,9 @@ namespace const auto y_cast = static_cast(y); if (x > 0 && y_cast < 0) return ((x - 1) / y_cast) - 1; - else if (x < 0 && y_cast > 0) + if (x < 0 && y_cast > 0) return ((x + 1) / y_cast) - 1; - else - return x / y_cast; + return x / y_cast; } /** Integer modulus, satisfying div(x, y)*y + mod(x, y) == x. @@ -69,8 +68,7 @@ namespace const auto r = x % y_cast; if ((x > 0 && y_cast < 0) || (x < 0 && y_cast > 0)) return r == 0 ? static_cast(0) : r + y_cast; - else - return r; + return r; } /** Like std::min(), but the type of operands may differ. @@ -87,10 +85,9 @@ namespace char c; if (!in.read(c)) throw Exception(ErrorCodes::CANNOT_PARSE_INPUT_ASSERTION_FAILED, "Cannot parse input: expected a digit at the end of stream"); - else if (c < '0' || c > '9') + if (c < '0' || c > '9') throw Exception(ErrorCodes::CANNOT_PARSE_INPUT_ASSERTION_FAILED, "Cannot read input: expected a digit but got something else"); - else - return c - '0'; + return c - '0'; } inline bool tryReadDigit(ReadBuffer & in, char & c) diff --git a/src/Functions/HasTokenImpl.h b/src/Functions/HasTokenImpl.h index 4943bf708c5..3be8228053c 100644 --- a/src/Functions/HasTokenImpl.h +++ b/src/Functions/HasTokenImpl.h @@ -56,12 +56,11 @@ struct HasTokenImpl std::ranges::fill(res_null->getData(), true); return; } - else if (has_separator) + if (has_separator) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Needle must not contain whitespace or separator characters"); - else if (pattern.empty()) + if (pattern.empty()) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Needle cannot be empty, because empty string isn't a token"); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected internal state"); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected internal state"); } size_t pattern_size = pattern.size(); diff --git a/src/Functions/IFunction.cpp b/src/Functions/IFunction.cpp index 31695fc95d5..4b96c51be7e 100644 --- a/src/Functions/IFunction.cpp +++ b/src/Functions/IFunction.cpp @@ -379,14 +379,13 @@ ColumnPtr IExecutableFunction::execute(const ColumnsWithTypeAndName & arguments, convertSparseColumnsToFull(columns_without_sparse); return executeWithoutSparseColumns(columns_without_sparse, result_type, input_rows_count, dry_run); } - else if (use_default_implementation_for_sparse_columns) + if (use_default_implementation_for_sparse_columns) { auto columns_without_sparse = arguments; convertSparseColumnsToFull(columns_without_sparse); return executeWithoutSparseColumns(columns_without_sparse, result_type, input_rows_count, dry_run); } - else - return executeWithoutSparseColumns(arguments, result_type, input_rows_count, dry_run); + return executeWithoutSparseColumns(arguments, result_type, input_rows_count, dry_run); } void IFunctionOverloadResolver::checkNumberOfArguments(size_t number_of_arguments) const @@ -440,8 +439,7 @@ DataTypePtr IFunctionOverloadResolver::getReturnType(const ColumnsWithTypeAndNam && num_full_low_cardinality_columns <= 1 && num_full_ordinary_columns == 0 && type_without_low_cardinality->canBeInsideLowCardinality()) return std::make_shared(type_without_low_cardinality); - else - return type_without_low_cardinality; + return type_without_low_cardinality; } return getReturnTypeWithoutLowCardinality(arguments); diff --git a/src/Functions/IFunctionCustomWeek.h b/src/Functions/IFunctionCustomWeek.h index ba0baa35819..497ccea428f 100644 --- a/src/Functions/IFunctionCustomWeek.h +++ b/src/Functions/IFunctionCustomWeek.h @@ -55,13 +55,11 @@ public: ? is_monotonic : is_not_monotonic; } - else - { - return Transform::FactorTransform::execute(UInt32(left.safeGet()), date_lut) - == Transform::FactorTransform::execute(UInt32(right.safeGet()), date_lut) - ? is_monotonic - : is_not_monotonic; - } + + return Transform::FactorTransform::execute(UInt32(left.safeGet()), date_lut) + == Transform::FactorTransform::execute(UInt32(right.safeGet()), date_lut) + ? is_monotonic + : is_not_monotonic; } protected: diff --git a/src/Functions/IFunctionDateOrDateTime.h b/src/Functions/IFunctionDateOrDateTime.h index 899aa2c305d..d9dc594e12b 100644 --- a/src/Functions/IFunctionDateOrDateTime.h +++ b/src/Functions/IFunctionDateOrDateTime.h @@ -76,32 +76,33 @@ public: == Transform::FactorTransform::execute(UInt16(right.safeGet()), *date_lut) ? is_monotonic : is_not_monotonic; } - else if (checkAndGetDataType(type_ptr)) + if (checkAndGetDataType(type_ptr)) { return Transform::FactorTransform::execute(Int32(left.safeGet()), *date_lut) - == Transform::FactorTransform::execute(Int32(right.safeGet()), *date_lut) - ? is_monotonic : is_not_monotonic; + == Transform::FactorTransform::execute(Int32(right.safeGet()), *date_lut) + ? is_monotonic + : is_not_monotonic; } - else if (checkAndGetDataType(type_ptr)) + if (checkAndGetDataType(type_ptr)) { return Transform::FactorTransform::execute(UInt32(left.safeGet()), *date_lut) - == Transform::FactorTransform::execute(UInt32(right.safeGet()), *date_lut) - ? is_monotonic : is_not_monotonic; + == Transform::FactorTransform::execute(UInt32(right.safeGet()), *date_lut) + ? is_monotonic + : is_not_monotonic; } - else - { - assert(checkAndGetDataType(type_ptr)); - const auto & left_date_time = left.safeGet(); - TransformDateTime64 transformer_left(left_date_time.getScale()); + assert(checkAndGetDataType(type_ptr)); - const auto & right_date_time = right.safeGet(); - TransformDateTime64 transformer_right(right_date_time.getScale()); + const auto & left_date_time = left.safeGet(); + TransformDateTime64 transformer_left(left_date_time.getScale()); - return transformer_left.execute(left_date_time.getValue(), *date_lut) + const auto & right_date_time = right.safeGet(); + TransformDateTime64 transformer_right(right_date_time.getScale()); + + return transformer_left.execute(left_date_time.getValue(), *date_lut) == transformer_right.execute(right_date_time.getValue(), *date_lut) - ? is_monotonic : is_not_monotonic; - } + ? is_monotonic + : is_not_monotonic; } } diff --git a/src/Functions/LeftRight.h b/src/Functions/LeftRight.h index bfa6f2194f4..aba075e44c1 100644 --- a/src/Functions/LeftRight.h +++ b/src/Functions/LeftRight.h @@ -111,30 +111,33 @@ public: if (const ColumnString * col = checkAndGetColumn(column_string.get())) return executeForSource(column_length, column_length_const, length_value, UTF8StringSource(*col), input_rows_count); - else if (const ColumnConst * col_const = checkAndGetColumnConst(column_string.get())) - return executeForSource(column_length, column_length_const, - length_value, ConstSource(*col_const), input_rows_count); - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), getName()); + if (const ColumnConst * col_const = checkAndGetColumnConst(column_string.get())) + return executeForSource( + column_length, column_length_const, length_value, ConstSource(*col_const), input_rows_count); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal column {} of first argument of function {}", + arguments[0].column->getName(), + getName()); } else { if (const ColumnString * col = checkAndGetColumn(column_string.get())) return executeForSource(column_length, column_length_const, length_value, StringSource(*col), input_rows_count); - else if (const ColumnFixedString * col_fixed = checkAndGetColumn(column_string.get())) - return executeForSource(column_length, column_length_const, - length_value, FixedStringSource(*col_fixed), input_rows_count); - else if (const ColumnConst * col_const = checkAndGetColumnConst(column_string.get())) - return executeForSource(column_length, column_length_const, - length_value, ConstSource(*col_const), input_rows_count); - else if (const ColumnConst * col_const_fixed = checkAndGetColumnConst(column_string.get())) - return executeForSource(column_length, column_length_const, - length_value, ConstSource(*col_const_fixed), input_rows_count); - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), getName()); + if (const ColumnFixedString * col_fixed = checkAndGetColumn(column_string.get())) + return executeForSource(column_length, column_length_const, length_value, FixedStringSource(*col_fixed), input_rows_count); + if (const ColumnConst * col_const = checkAndGetColumnConst(column_string.get())) + return executeForSource( + column_length, column_length_const, length_value, ConstSource(*col_const), input_rows_count); + if (const ColumnConst * col_const_fixed = checkAndGetColumnConst(column_string.get())) + return executeForSource( + column_length, column_length_const, length_value, ConstSource(*col_const_fixed), input_rows_count); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal column {} of first argument of function {}", + arguments[0].column->getName(), + getName()); } } }; diff --git a/src/Functions/MatchImpl.h b/src/Functions/MatchImpl.h index 7dc93ba79e0..e312594219b 100644 --- a/src/Functions/MatchImpl.h +++ b/src/Functions/MatchImpl.h @@ -48,23 +48,22 @@ inline bool likePatternIsSubstring(std::string_view pattern, String & res) if (pos == end) /// pattern ends with \% --> trailing % is to be taken literally and pattern doesn't qualify for substring search return false; - else + + switch (*pos) { - switch (*pos) - { - /// Known LIKE escape sequences: - case '%': - case '_': - case '\\': - res += *pos; - break; - /// For all other escape sequences, the backslash loses its special meaning - default: - res += '\\'; - res += *pos; - break; - } + /// Known LIKE escape sequences: + case '%': + case '_': + case '\\': + res += *pos; + break; + /// For all other escape sequences, the backslash loses its special meaning + default: + res += '\\'; + res += *pos; + break; } + break; default: res += *pos; diff --git a/src/Functions/PositionImpl.h b/src/Functions/PositionImpl.h index e525b5fab57..9bebff0e130 100644 --- a/src/Functions/PositionImpl.h +++ b/src/Functions/PositionImpl.h @@ -231,22 +231,20 @@ struct PositionImpl } return; } - else - { - /// Needle is empty and start_pos is not constant - for (size_t i = 0; i < input_rows_count; ++i) - { - size_t haystack_size = Impl::countChars( - reinterpret_cast(pos), reinterpret_cast(pos + haystack_offsets[i] - prev_offset - 1)); - UInt64 start = start_pos->getUInt(i); - start = std::max(static_cast(1), start); - res[i] = (start <= haystack_size + 1) ? start : 0; - pos = begin + haystack_offsets[i]; - prev_offset = haystack_offsets[i]; - } - return; + /// Needle is empty and start_pos is not constant + for (size_t i = 0; i < input_rows_count; ++i) + { + size_t haystack_size = Impl::countChars( + reinterpret_cast(pos), reinterpret_cast(pos + haystack_offsets[i] - prev_offset - 1)); + UInt64 start = start_pos->getUInt(i); + start = std::max(static_cast(1), start); + res[i] = (start <= haystack_size + 1) ? start : 0; + + pos = begin + haystack_offsets[i]; + prev_offset = haystack_offsets[i]; } + return; } /// Current index in the array of strings. diff --git a/src/Functions/Regexps.h b/src/Functions/Regexps.h index b317d786fab..05b509b3351 100644 --- a/src/Functions/Regexps.h +++ b/src/Functions/Regexps.h @@ -254,8 +254,8 @@ inline Regexps constructRegexps(const std::vector & str_patterns, [[mayb if (error->expression < 0) throw Exception::createRuntime(ErrorCodes::LOGICAL_ERROR, String(error->message)); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Pattern '{}' failed with error '{}'", str_patterns[error->expression], String(error->message)); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, "Pattern '{}' failed with error '{}'", str_patterns[error->expression], String(error->message)); } ProfileEvents::increment(ProfileEvents::RegexpWithMultipleNeedlesCreated); diff --git a/src/Functions/URL/FirstSignificantSubdomainCustomImpl.h b/src/Functions/URL/FirstSignificantSubdomainCustomImpl.h index 22fec17654c..6462c968bfa 100644 --- a/src/Functions/URL/FirstSignificantSubdomainCustomImpl.h +++ b/src/Functions/URL/FirstSignificantSubdomainCustomImpl.h @@ -75,9 +75,8 @@ public: vector(tld_lookup, col->getChars(), col->getOffsets(), col_res->getChars(), col_res->getOffsets(), input_rows_count); return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } static void vector(FirstSignificantSubdomainCustomLookup & tld_lookup, diff --git a/src/Functions/URL/URLHierarchy.cpp b/src/Functions/URL/URLHierarchy.cpp index 0f565df8172..72aab260030 100644 --- a/src/Functions/URL/URLHierarchy.cpp +++ b/src/Functions/URL/URLHierarchy.cpp @@ -72,8 +72,7 @@ public: pos = end; return false; } - else - pos += 3; + pos += 3; /// The domain for simplicity is everything that after the protocol and the two slashes, until the next slash or `?` or `#` while (pos < end && !(*pos == '/' || *pos == '?' || *pos == '#')) diff --git a/src/Functions/URL/URLPathHierarchy.cpp b/src/Functions/URL/URLPathHierarchy.cpp index 2cb5995e375..06fae644f67 100644 --- a/src/Functions/URL/URLPathHierarchy.cpp +++ b/src/Functions/URL/URLPathHierarchy.cpp @@ -70,8 +70,7 @@ public: token_end = end; return true; } - else - pos += 3; + pos += 3; /// The domain for simplicity is everything that after the protocol and two slashes, until the next slash or `?` or `#` while (pos < end && !(*pos == '/' || *pos == '?' || *pos == '#')) diff --git a/src/Functions/URL/cutURLParameter.cpp b/src/Functions/URL/cutURLParameter.cpp index 4439e79e962..9f2b4db8aad 100644 --- a/src/Functions/URL/cutURLParameter.cpp +++ b/src/Functions/URL/cutURLParameter.cpp @@ -74,10 +74,8 @@ public: vector(col->getChars(), col->getOffsets(), col_needle, col_needle_const_array, vec_res, offsets_res, input_rows_count); return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, - "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } static void cutURL(ColumnString::Chars & data, String pattern, size_t prev_offset, size_t & cur_offset) diff --git a/src/Functions/URL/decodeURLComponent.cpp b/src/Functions/URL/decodeURLComponent.cpp index bf4aaa6d5e3..1096586e01a 100644 --- a/src/Functions/URL/decodeURLComponent.cpp +++ b/src/Functions/URL/decodeURLComponent.cpp @@ -57,7 +57,7 @@ static size_t decodeURL(const char * __restrict src, size_t src_size, char * __r { break; } - else if (*src_curr_pos == '+') + if (*src_curr_pos == '+') { if (!plus_as_space) { diff --git a/src/Functions/URL/extractURLParameter.cpp b/src/Functions/URL/extractURLParameter.cpp index 590c2779d9c..8f92496fdcd 100644 --- a/src/Functions/URL/extractURLParameter.cpp +++ b/src/Functions/URL/extractURLParameter.cpp @@ -55,11 +55,9 @@ struct ExtractURLParameterImpl param_begin += param_len; continue; } - else - { - param_begin += param_len; - break; - } + + param_begin += param_len; + break; } } diff --git a/src/Functions/URL/extractURLParameterNames.cpp b/src/Functions/URL/extractURLParameterNames.cpp index b3d51d02162..0aca2f387ae 100644 --- a/src/Functions/URL/extractURLParameterNames.cpp +++ b/src/Functions/URL/extractURLParameterNames.cpp @@ -70,8 +70,7 @@ public: pos = find_first_symbols<'=', '&', '#', '?'>(pos, end); if (pos == end) return false; - else - token_end = pos; + token_end = pos; if (*pos == '?') { diff --git a/src/Functions/URL/netloc.cpp b/src/Functions/URL/netloc.cpp index d1ca4fa1614..4cfa5cd6e66 100644 --- a/src/Functions/URL/netloc.cpp +++ b/src/Functions/URL/netloc.cpp @@ -3,6 +3,8 @@ #include #include +#include + namespace DB { @@ -124,15 +126,14 @@ struct ExtractNetloc case '[': case ']': return pos > start_of_host - ? std::string_view(start_of_host, std::min(std::min(pos, question_mark_pos), slash_pos) - start_of_host) + ? std::string_view(start_of_host, std::min({pos, question_mark_pos, slash_pos}) - start_of_host) : std::string_view(); } } if (has_identification) return std::string_view(start_of_host, pos - start_of_host); - else - return std::string_view(start_of_host, std::min(std::min(std::min(pos, question_mark_pos), slash_pos), hostname_end) - start_of_host); + return std::string_view(start_of_host, std::min({pos, question_mark_pos, slash_pos, hostname_end}) - start_of_host); } static void execute(Pos data, size_t size, Pos & res_data, size_t & res_size) diff --git a/src/Functions/URL/port.cpp b/src/Functions/URL/port.cpp index 7492ebcb4e9..7abeaba7b90 100644 --- a/src/Functions/URL/port.cpp +++ b/src/Functions/URL/port.cpp @@ -67,9 +67,8 @@ struct FunctionPortImpl : public IFunction vector(default_port, url_strs->getChars(), url_strs->getOffsets(), vec_res, input_rows_count); return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } private: diff --git a/src/Functions/UTCTimestampTransform.cpp b/src/Functions/UTCTimestampTransform.cpp index 35015188078..619951b8113 100644 --- a/src/Functions/UTCTimestampTransform.cpp +++ b/src/Functions/UTCTimestampTransform.cpp @@ -93,7 +93,7 @@ namespace } return result_column; } - else if (WhichDataType(arg1.type).isDateTime64()) + if (WhichDataType(arg1.type).isDateTime64()) { const auto & date_time_col = checkAndGetColumn(*arg1.column); const DataTypeDateTime64 * date_time_type = static_cast(arg1.type.get()); @@ -114,8 +114,7 @@ namespace } return result_column; } - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Function {}'s 1st argument can only be datetime/datatime64. ", name); + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Function {}'s 1st argument can only be datetime/datatime64. ", name); } }; diff --git a/src/Functions/UserDefined/ExternalUserDefinedExecutableFunctionsLoader.cpp b/src/Functions/UserDefined/ExternalUserDefinedExecutableFunctionsLoader.cpp index eb16863fac9..fcb6c2e0dcc 100644 --- a/src/Functions/UserDefined/ExternalUserDefinedExecutableFunctionsLoader.cpp +++ b/src/Functions/UserDefined/ExternalUserDefinedExecutableFunctionsLoader.cpp @@ -54,7 +54,7 @@ namespace auto semicolon_pos = command_value.find(':', start_parameter_pos); if (semicolon_pos == std::string::npos) break; - else if (semicolon_pos > end_parameter_pos) + if (semicolon_pos > end_parameter_pos) continue; std::string parameter_name(command_value.data() + start_parameter_pos + 1, command_value.data() + semicolon_pos); diff --git a/src/Functions/UserDefined/UserDefinedSQLObjectsDiskStorage.cpp b/src/Functions/UserDefined/UserDefinedSQLObjectsDiskStorage.cpp index a3af0b66365..247c48b83cc 100644 --- a/src/Functions/UserDefined/UserDefinedSQLObjectsDiskStorage.cpp +++ b/src/Functions/UserDefined/UserDefinedSQLObjectsDiskStorage.cpp @@ -204,7 +204,7 @@ bool UserDefinedSQLObjectsDiskStorage::storeObjectImpl( { if (throw_if_exists) throw Exception(ErrorCodes::FUNCTION_ALREADY_EXISTS, "User-defined function '{}' already exists", object_name); - else if (!replace_if_exists) + if (!replace_if_exists) return false; } @@ -255,8 +255,7 @@ bool UserDefinedSQLObjectsDiskStorage::removeObjectImpl( { if (throw_if_not_exists) throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "User-defined function '{}' doesn't exist", object_name); - else - return false; + return false; } LOG_TRACE(log, "Object {} removed", backQuote(object_name)); diff --git a/src/Functions/UserDefined/UserDefinedSQLObjectsStorageBase.cpp b/src/Functions/UserDefined/UserDefinedSQLObjectsStorageBase.cpp index 1df57f76f23..5c4674744d9 100644 --- a/src/Functions/UserDefined/UserDefinedSQLObjectsStorageBase.cpp +++ b/src/Functions/UserDefined/UserDefinedSQLObjectsStorageBase.cpp @@ -105,7 +105,7 @@ bool UserDefinedSQLObjectsStorageBase::storeObject( { if (throw_if_exists) throw Exception(ErrorCodes::FUNCTION_ALREADY_EXISTS, "User-defined object '{}' already exists", object_name); - else if (!replace_if_exists) + if (!replace_if_exists) return false; } @@ -136,8 +136,7 @@ bool UserDefinedSQLObjectsStorageBase::removeObject( { if (throw_if_not_exists) throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "User-defined object '{}' doesn't exist", object_name); - else - return false; + return false; } bool removed = removeObjectImpl( diff --git a/src/Functions/UserDefined/UserDefinedSQLObjectsZooKeeperStorage.cpp b/src/Functions/UserDefined/UserDefinedSQLObjectsZooKeeperStorage.cpp index e7e3d5932f4..00927d9848f 100644 --- a/src/Functions/UserDefined/UserDefinedSQLObjectsZooKeeperStorage.cpp +++ b/src/Functions/UserDefined/UserDefinedSQLObjectsZooKeeperStorage.cpp @@ -234,7 +234,7 @@ bool UserDefinedSQLObjectsZooKeeperStorage::storeObjectImpl( { if (throw_if_exists) throw Exception(ErrorCodes::FUNCTION_ALREADY_EXISTS, "User-defined function '{}' already exists", object_name); - else if (!replace_if_exists) + if (!replace_if_exists) return false; code = zookeeper->trySet(path, create_statement); @@ -276,8 +276,7 @@ bool UserDefinedSQLObjectsZooKeeperStorage::removeObjectImpl( { if (throw_if_not_exists) throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "User-defined object '{}' doesn't exist", object_name); - else - return false; + return false; } LOG_DEBUG(log, "Object {} removed", backQuote(object_name)); diff --git a/src/Functions/UserDefined/createUserDefinedSQLObjectsStorage.cpp b/src/Functions/UserDefined/createUserDefinedSQLObjectsStorage.cpp index 0b1a74884cf..9f3e79c57f9 100644 --- a/src/Functions/UserDefined/createUserDefinedSQLObjectsStorage.cpp +++ b/src/Functions/UserDefined/createUserDefinedSQLObjectsStorage.cpp @@ -35,12 +35,10 @@ std::unique_ptr createUserDefinedSQLObjectsStorag } return std::make_unique(global_context, config.getString(zookeeper_path_key)); } - else - { - String default_path = fs::path{global_context->getPath()} / "user_defined" / ""; - String path = config.getString(disk_path_key, default_path); - return std::make_unique(global_context, path); - } + + String default_path = fs::path{global_context->getPath()} / "user_defined" / ""; + String path = config.getString(disk_path_key, default_path); + return std::make_unique(global_context, path); } } diff --git a/src/Functions/addressToLine.h b/src/Functions/addressToLine.h index 5c1611fe173..de986597be4 100644 --- a/src/Functions/addressToLine.h +++ b/src/Functions/addressToLine.h @@ -106,11 +106,9 @@ protected: setResult(result, location, frames); return result; } - else - return {object->name}; + return {object->name}; } - else - return {}; + return {}; } ResultT implCached(uintptr_t addr) const diff --git a/src/Functions/appendTrailingCharIfAbsent.cpp b/src/Functions/appendTrailingCharIfAbsent.cpp index 0e57d5c55ce..f894c7825b6 100644 --- a/src/Functions/appendTrailingCharIfAbsent.cpp +++ b/src/Functions/appendTrailingCharIfAbsent.cpp @@ -106,9 +106,8 @@ private: dst_data.resize_assume_reserved(dst_offset); return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/array/FunctionArrayMapped.h b/src/Functions/array/FunctionArrayMapped.h index 3c8dc04de46..f4832431f04 100644 --- a/src/Functions/array/FunctionArrayMapped.h +++ b/src/Functions/array/FunctionArrayMapped.h @@ -206,49 +206,47 @@ public: return Impl::getReturnType(nested_type, nested_type); } - else - { - if (arguments.size() > 2 + num_fixed_params && Impl::needOneArray()) - throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "Function {} needs one argument with data", getName()); - const auto * data_type_function = checkAndGetDataType(arguments[0].type.get()); + if (arguments.size() > 2 + num_fixed_params && Impl::needOneArray()) + throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "Function {} needs one argument with data", getName()); - if (!data_type_function) - throw Exception( - ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "First argument for function {} must be a function. Actual {}", - getName(), - arguments[0].type->getName()); + const auto * data_type_function = checkAndGetDataType(arguments[0].type.get()); - if constexpr (num_fixed_params) - Impl::checkArguments(getName(), arguments.data() + 1); + if (!data_type_function) + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "First argument for function {} must be a function. Actual {}", + getName(), + arguments[0].type->getName()); - /// The types of the remaining arguments are already checked in getLambdaArgumentTypes. + if constexpr (num_fixed_params) + Impl::checkArguments(getName(), arguments.data() + 1); - DataTypePtr return_type = removeLowCardinality(data_type_function->getReturnType()); + /// The types of the remaining arguments are already checked in getLambdaArgumentTypes. - /// Special cases when we need boolean lambda result: - /// - lambda may return Nullable(UInt8) column, in this case after lambda execution we will - /// replace all NULLs with 0 and return nested UInt8 column. - /// - lambda may return Nothing or Nullable(Nothing) because of default implementation of functions - /// for these types. In this case we will just create UInt8 const column full of 0. - if (Impl::needBoolean() && !isUInt8(removeNullable(return_type)) && !isNothing(removeNullable(return_type))) - throw Exception( - ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Expression for function {} must return UInt8 or Nullable(UInt8), found {}", - getName(), - return_type->getName()); + DataTypePtr return_type = removeLowCardinality(data_type_function->getReturnType()); - if (arguments.size() < 2 + num_fixed_params) - throw DB::Exception(ErrorCodes::LOGICAL_ERROR, "Incorrect number of arguments: {}", arguments.size()); + /// Special cases when we need boolean lambda result: + /// - lambda may return Nullable(UInt8) column, in this case after lambda execution we will + /// replace all NULLs with 0 and return nested UInt8 column. + /// - lambda may return Nothing or Nullable(Nothing) because of default implementation of functions + /// for these types. In this case we will just create UInt8 const column full of 0. + if (Impl::needBoolean() && !isUInt8(removeNullable(return_type)) && !isNothing(removeNullable(return_type))) + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Expression for function {} must return UInt8 or Nullable(UInt8), found {}", + getName(), + return_type->getName()); - const auto * first_array_type = checkAndGetDataType(arguments[1 + num_fixed_params].type.get()); - if (!first_array_type) - throw DB::Exception( - ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Unsupported type {}", arguments[1 + num_fixed_params].type->getName()); + if (arguments.size() < 2 + num_fixed_params) + throw DB::Exception(ErrorCodes::LOGICAL_ERROR, "Incorrect number of arguments: {}", arguments.size()); - return Impl::getReturnType(return_type, first_array_type->getNestedType()); - } + const auto * first_array_type = checkAndGetDataType(arguments[1 + num_fixed_params].type.get()); + if (!first_array_type) + throw DB::Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Unsupported type {}", arguments[1 + num_fixed_params].type->getName()); + + return Impl::getReturnType(return_type, first_array_type->getNestedType()); } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t /*input_rows_count*/) const override diff --git a/src/Functions/array/arrayAll.cpp b/src/Functions/array/arrayAll.cpp index 82ad874e84a..3ed73ac9931 100644 --- a/src/Functions/array/arrayAll.cpp +++ b/src/Functions/array/arrayAll.cpp @@ -22,21 +22,19 @@ ColumnPtr ArrayAllImpl::execute(const ColumnArray & array, ColumnPtr mapped) if (column_filter_const->getValue()) return DataTypeUInt8().createColumnConst(array.size(), 1u); - else + + const IColumn::Offsets & offsets = array.getOffsets(); + auto out_column = ColumnUInt8::create(offsets.size()); + ColumnUInt8::Container & out_all = out_column->getData(); + + size_t pos = 0; + for (size_t i = 0; i < offsets.size(); ++i) { - const IColumn::Offsets & offsets = array.getOffsets(); - auto out_column = ColumnUInt8::create(offsets.size()); - ColumnUInt8::Container & out_all = out_column->getData(); - - size_t pos = 0; - for (size_t i = 0; i < offsets.size(); ++i) - { - out_all[i] = offsets[i] == pos; - pos = offsets[i]; - } - - return out_column; + out_all[i] = offsets[i] == pos; + pos = offsets[i]; } + + return out_column; } const IColumn::Filter & filter = column_filter->getData(); diff --git a/src/Functions/array/arrayCount.cpp b/src/Functions/array/arrayCount.cpp index 398ff5941d3..9e893d5a4e3 100644 --- a/src/Functions/array/arrayCount.cpp +++ b/src/Functions/array/arrayCount.cpp @@ -52,8 +52,7 @@ struct ArrayCountImpl return out_column; } - else - return DataTypeUInt32().createColumnConst(array.size(), 0u); + return DataTypeUInt32().createColumnConst(array.size(), 0u); } const IColumn::Filter & filter = column_filter->getData(); diff --git a/src/Functions/array/arrayCumSum.cpp b/src/Functions/array/arrayCumSum.cpp index 7ad7b90cf0a..fda32e944ea 100644 --- a/src/Functions/array/arrayCumSum.cpp +++ b/src/Functions/array/arrayCumSum.cpp @@ -164,8 +164,7 @@ struct ArrayCumSumImpl || executeType(mapped, array, res) || executeType(mapped, array, res) || executeType(mapped, array, res) || executeType(mapped, array, res)) return res; - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Unexpected column for arrayCumSum: {}", mapped->getName()); + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Unexpected column for arrayCumSum: {}", mapped->getName()); } }; diff --git a/src/Functions/array/arrayCumSumNonNegative.cpp b/src/Functions/array/arrayCumSumNonNegative.cpp index cb21a853ea0..1986539d8d2 100644 --- a/src/Functions/array/arrayCumSumNonNegative.cpp +++ b/src/Functions/array/arrayCumSumNonNegative.cpp @@ -129,8 +129,7 @@ struct ArrayCumSumNonNegativeImpl || executeType(mapped, array, res) || executeType(mapped, array, res) || executeType(mapped, array, res) || executeType(mapped, array, res)) return res; - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Unexpected column for arrayCumSumNonNegativeImpl: {}", mapped->getName()); + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Unexpected column for arrayCumSumNonNegativeImpl: {}", mapped->getName()); } }; diff --git a/src/Functions/array/arrayDifference.cpp b/src/Functions/array/arrayDifference.cpp index 857a88b82a2..450ccc7f93f 100644 --- a/src/Functions/array/arrayDifference.cpp +++ b/src/Functions/array/arrayDifference.cpp @@ -154,8 +154,7 @@ struct ArrayDifferenceImpl || executeType(mapped, array, res) || executeType(mapped, array, res) || executeType(mapped, array, res)) return res; - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Unexpected column for arrayDifference: {}", mapped->getName()); + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Unexpected column for arrayDifference: {}", mapped->getName()); } }; diff --git a/src/Functions/array/arrayDistance.cpp b/src/Functions/array/arrayDistance.cpp index 6ed4bf24f99..a1f48747eb6 100644 --- a/src/Functions/array/arrayDistance.cpp +++ b/src/Functions/array/arrayDistance.cpp @@ -450,7 +450,7 @@ private: { return executeWithLeftArgConst(col_x, col_y, input_rows_count, arguments); } - else if (typeid_cast(col_y.get())) + if (typeid_cast(col_y.get())) { return executeWithLeftArgConst(col_y, col_x, input_rows_count, arguments); } diff --git a/src/Functions/array/arrayDotProduct.cpp b/src/Functions/array/arrayDotProduct.cpp index 4551140acc3..faae8917b6d 100644 --- a/src/Functions/array/arrayDotProduct.cpp +++ b/src/Functions/array/arrayDotProduct.cpp @@ -250,7 +250,7 @@ private: { return executeWithLeftArgConst(col_x, col_y, input_rows_count); } - else if (typeid_cast(col_y.get())) + if (typeid_cast(col_y.get())) { return executeWithLeftArgConst(col_y, col_x, input_rows_count); } diff --git a/src/Functions/array/arrayElement.cpp b/src/Functions/array/arrayElement.cpp index 0f8bbef29f4..71cb0e2ea75 100644 --- a/src/Functions/array/arrayElement.cpp +++ b/src/Functions/array/arrayElement.cpp @@ -1101,8 +1101,8 @@ ColumnPtr FunctionArrayElement::executeArrayStringConst( if (col_nullable) return ColumnArray::create(ColumnNullable::create(std::move(res_string), std::move(res_string_null_map)), std::move(res_offsets)); - else - return ColumnArray::create(std::move(res_string), std::move(res_offsets)); + + return ColumnArray::create(std::move(res_string), std::move(res_offsets)); } template @@ -1408,8 +1408,8 @@ ColumnPtr FunctionArrayElement::removeNullableIfNeeded(const ColumnPtr & c /// To keep return type consistency, we need to unwrap the Nullable column returned by ArrayElementOrNull(T1) and ArrayElementOrNull(T2) return nullable_column->getNestedColumnPtr(); } - else - return column; + + return column; } template @@ -2055,55 +2055,53 @@ ColumnPtr FunctionArrayElement::executeImpl( if (builder && res->canBeInsideNullable()) return ColumnNullable::create(res, std::move(builder).getNullMapColumnPtr()); - else - return res; + + return res; + } + + /// Perform initializations. + ArrayImpl::NullMapBuilder builder; + ColumnsWithTypeAndName source_columns; + + const DataTypePtr & input_type + = typeid_cast(*typeid_cast(*arguments[0].type).getNestedType()) + .getNestedType(); + + DataTypePtr tmp_ret_type = removeNullable(result_type); + + if (col_array) + { + const auto & nullable_col = typeid_cast(col_array->getData()); + const auto & nested_col = nullable_col.getNestedColumnPtr(); + + /// Put nested_col inside a ColumnArray. + source_columns = { + {ColumnArray::create(nested_col, col_array->getOffsetsPtr()), std::make_shared(input_type), ""}, + arguments[1], + }; + + builder.initSource(nullable_col.getNullMapData().data()); } else { - /// Perform initializations. - ArrayImpl::NullMapBuilder builder; - ColumnsWithTypeAndName source_columns; + /// ColumnConst(ColumnArray(ColumnNullable(...))) + const auto & nullable_col = assert_cast(col_const_array->getData()); + const auto & nested_col = nullable_col.getNestedColumnPtr(); - const DataTypePtr & input_type - = typeid_cast(*typeid_cast(*arguments[0].type).getNestedType()) - .getNestedType(); + source_columns = { + {ColumnConst::create(ColumnArray::create(nested_col, col_const_array->getOffsetsPtr()), input_rows_count), + std::make_shared(input_type), + ""}, + arguments[1], + }; - DataTypePtr tmp_ret_type = removeNullable(result_type); - - if (col_array) - { - const auto & nullable_col = typeid_cast(col_array->getData()); - const auto & nested_col = nullable_col.getNestedColumnPtr(); - - /// Put nested_col inside a ColumnArray. - source_columns = { - {ColumnArray::create(nested_col, col_array->getOffsetsPtr()), std::make_shared(input_type), ""}, - arguments[1], - }; - - builder.initSource(nullable_col.getNullMapData().data()); - } - else - { - /// ColumnConst(ColumnArray(ColumnNullable(...))) - const auto & nullable_col = assert_cast(col_const_array->getData()); - const auto & nested_col = nullable_col.getNestedColumnPtr(); - - source_columns = { - {ColumnConst::create(ColumnArray::create(nested_col, col_const_array->getOffsetsPtr()), input_rows_count), - std::make_shared(input_type), - ""}, - arguments[1], - }; - - builder.initSource(nullable_col.getNullMapData().data()); - } - - auto res = perform(source_columns, tmp_ret_type, builder, input_rows_count); - - /// Store the result. - return ColumnNullable::create(res, builder ? std::move(builder).getNullMapColumnPtr() : ColumnUInt8::create()); + builder.initSource(nullable_col.getNullMapData().data()); } + + auto res = perform(source_columns, tmp_ret_type, builder, input_rows_count); + + /// Store the result. + return ColumnNullable::create(res, builder ? std::move(builder).getNullMapColumnPtr() : ColumnUInt8::create()); } template @@ -2116,9 +2114,9 @@ ColumnPtr FunctionArrayElement::perform( ColumnPtr res; if ((res = executeTuple(arguments, input_rows_count))) return res; - else if ((res = executeMap2(arguments, input_rows_count))) + if ((res = executeMap2(arguments, input_rows_count))) return res; - else if (!isColumnConst(*arguments[1].column)) + if (!isColumnConst(*arguments[1].column)) { if (!((res = executeArgument(arguments, result_type, builder, input_rows_count)) || (res = executeArgument(arguments, result_type, builder, input_rows_count)) diff --git a/src/Functions/array/arrayEnumerate.cpp b/src/Functions/array/arrayEnumerate.cpp index 175989912dd..97749f7758c 100644 --- a/src/Functions/array/arrayEnumerate.cpp +++ b/src/Functions/array/arrayEnumerate.cpp @@ -67,11 +67,9 @@ public: return ColumnArray::create(std::move(res_nested), array->getOffsetsPtr()); } - else - { - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), getName()); - } + + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/array/arrayExists.cpp b/src/Functions/array/arrayExists.cpp index 2c8a7648088..e75c765664a 100644 --- a/src/Functions/array/arrayExists.cpp +++ b/src/Functions/array/arrayExists.cpp @@ -35,8 +35,7 @@ ColumnPtr ArrayExistsImpl::execute(const ColumnArray & array, ColumnPtr mapped) return out_column; } - else - return DataTypeUInt8().createColumnConst(array.size(), 0u); + return DataTypeUInt8().createColumnConst(array.size(), 0u); } const IColumn::Filter & filter = column_filter->getData(); diff --git a/src/Functions/array/arrayFilter.cpp b/src/Functions/array/arrayFilter.cpp index 72878edfe79..0b1fbba9090 100644 --- a/src/Functions/array/arrayFilter.cpp +++ b/src/Functions/array/arrayFilter.cpp @@ -22,10 +22,7 @@ ColumnPtr ArrayFilterImpl::execute(const ColumnArray & array, ColumnPtr mapped) if (column_filter_const->getValue()) return array.clone(); - else - return ColumnArray::create( - array.getDataPtr()->cloneEmpty(), - ColumnArray::ColumnOffsets::create(array.size(), 0)); + return ColumnArray::create(array.getDataPtr()->cloneEmpty(), ColumnArray::ColumnOffsets::create(array.size(), 0)); } const IColumn::Filter & filter = column_filter->getData(); diff --git a/src/Functions/array/arrayFirstLast.cpp b/src/Functions/array/arrayFirstLast.cpp index e54d47a3f97..f0f83337a24 100644 --- a/src/Functions/array/arrayFirstLast.cpp +++ b/src/Functions/array/arrayFirstLast.cpp @@ -105,19 +105,17 @@ struct ArrayFirstLastImpl return out; } - else + + auto out = array.getData().cloneEmpty(); + out->insertManyDefaults(array.size()); + + if constexpr (element_not_exists_strategy == ArrayFirstLastElementNotExistsStrategy::Null) { - auto out = array.getData().cloneEmpty(); - out->insertManyDefaults(array.size()); - - if constexpr (element_not_exists_strategy == ArrayFirstLastElementNotExistsStrategy::Null) - { - auto col_null_map_to = ColumnUInt8::create(out->size(), true); - return createNullableColumn(std::move(out), std::move(col_null_map_to)); - } - - return out; + auto col_null_map_to = ColumnUInt8::create(out->size(), true); + return createNullableColumn(std::move(out), std::move(col_null_map_to)); } + + return out; } const auto & filter = column_filter->getData(); diff --git a/src/Functions/array/arrayFirstLastIndex.cpp b/src/Functions/array/arrayFirstLastIndex.cpp index 54c9cb487de..60828122572 100644 --- a/src/Functions/array/arrayFirstLastIndex.cpp +++ b/src/Functions/array/arrayFirstLastIndex.cpp @@ -68,10 +68,8 @@ struct ArrayFirstLastIndexImpl return out_column; } - else - { - return DataTypeUInt32().createColumnConst(array.size(), 0u); - } + + return DataTypeUInt32().createColumnConst(array.size(), 0u); } const auto & filter = column_filter->getData(); diff --git a/src/Functions/array/arrayIndex.h b/src/Functions/array/arrayIndex.h index 0782f109187..e6ea9f4c4ee 100644 --- a/src/Functions/array/arrayIndex.h +++ b/src/Functions/array/arrayIndex.h @@ -497,63 +497,55 @@ private: { return executeOnNonNullable(arguments, result_type); } - else - { - /** + + /** * To correctly process the Nullable values (either #col_array, #arg_column or both) we create a new columns * and operate on it. The columns structure follows: * {0, 1, 2, 3, 4} * {data (array) argument, "value" argument, data null map, "value" null map, function result}. */ - ColumnsWithTypeAndName source_columns(4); + ColumnsWithTypeAndName source_columns(4); - if (nullable) - { - const auto & nested_col = nullable->getNestedColumnPtr(); + if (nullable) + { + const auto & nested_col = nullable->getNestedColumnPtr(); - auto & data = source_columns[0]; + auto & data = source_columns[0]; - data.column = ColumnArray::create(nested_col, col_array->getOffsetsPtr()); - data.type = std::make_shared( - static_cast( - *static_cast( - *arguments[0].type - ).getNestedType() - ).getNestedType()); + data.column = ColumnArray::create(nested_col, col_array->getOffsetsPtr()); + data.type = std::make_shared( + static_cast(*static_cast(*arguments[0].type).getNestedType()) + .getNestedType()); - auto & null_map = source_columns[2]; + auto & null_map = source_columns[2]; - null_map.column = nullable->getNullMapColumnPtr(); - null_map.type = std::make_shared(); - } - else - { - auto & data = source_columns[0]; - data = arguments[0]; - } - - if (arg_nullable) - { - auto & arg = source_columns[1]; - arg.column = arg_nullable->getNestedColumnPtr(); - arg.type = - static_cast( - *arguments[1].type - ).getNestedType(); - - auto & null_map = source_columns[3]; - null_map.column = arg_nullable->getNullMapColumnPtr(); - null_map.type = std::make_shared(); - } - else - { - auto & arg = source_columns[1]; - arg = arguments[1]; - } - - /// Now perform the function. - return executeOnNonNullable(source_columns, result_type); + null_map.column = nullable->getNullMapColumnPtr(); + null_map.type = std::make_shared(); } + else + { + auto & data = source_columns[0]; + data = arguments[0]; + } + + if (arg_nullable) + { + auto & arg = source_columns[1]; + arg.column = arg_nullable->getNestedColumnPtr(); + arg.type = static_cast(*arguments[1].type).getNestedType(); + + auto & null_map = source_columns[3]; + null_map.column = arg_nullable->getNullMapColumnPtr(); + null_map.type = std::make_shared(); + } + else + { + auto & arg = source_columns[1]; + arg = arguments[1]; + } + + /// Now perform the function. + return executeOnNonNullable(source_columns, result_type); } #define INTEGRAL_PACK UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, Float64 @@ -876,53 +868,51 @@ private: return result_type->createColumnConst(item_arg->size(), current); } - else + + /// Null map of the 2nd function argument, if it applies. + const NullMap * null_map = nullptr; + + if (arguments.size() > 2) + if (const auto & col = arguments[3].column; col) + null_map = &assert_cast(*col).getData(); + + const size_t size = item_arg->size(); + auto col_res = ResultColumnType::create(size); + + auto & data = col_res->getData(); + + for (size_t row = 0; row < size; ++row) { - /// Null map of the 2nd function argument, if it applies. - const NullMap * null_map = nullptr; + const auto & value = (*item_arg)[row]; - if (arguments.size() > 2) - if (const auto & col = arguments[3].column; col) - null_map = &assert_cast(*col).getData(); + data[row] = 0; - const size_t size = item_arg->size(); - auto col_res = ResultColumnType::create(size); - - auto & data = col_res->getData(); - - for (size_t row = 0; row < size; ++row) + for (size_t i = 0, arr_size = arr.size(); i < arr_size; ++i) { - const auto & value = (*item_arg)[row]; - - data[row] = 0; - - for (size_t i = 0, arr_size = arr.size(); i < arr_size; ++i) + if (arr[i].isNull()) { - if (arr[i].isNull()) - { - if (!null_map) - continue; + if (!null_map) + continue; - if (!(*null_map)[row]) - continue; - } - else - { - if (null_map && (*null_map)[row]) - continue; - if (!applyVisitor(FieldVisitorAccurateEquals(), arr[i], value)) - continue; - } - - ConcreteAction::apply(data[row], i); - - if constexpr (!ConcreteAction::resume_execution) - break; + if (!(*null_map)[row]) + continue; + } + else + { + if (null_map && (*null_map)[row]) + continue; + if (!applyVisitor(FieldVisitorAccurateEquals(), arr[i], value)) + continue; } - } - return col_res; + ConcreteAction::apply(data[row], i); + + if constexpr (!ConcreteAction::resume_execution) + break; + } } + + return col_res; } static ColumnPtr executeNothing(const ColumnsWithTypeAndName & arguments) diff --git a/src/Functions/array/arrayIntersect.cpp b/src/Functions/array/arrayIntersect.cpp index 316cc869ca1..64bf75bfd50 100644 --- a/src/Functions/array/arrayIntersect.cpp +++ b/src/Functions/array/arrayIntersect.cpp @@ -219,23 +219,26 @@ ColumnPtr FunctionArrayIntersect::castRemoveNullable(const ColumnPtr & col } return castRemoveNullable(nested, data_type); } - else if (const auto * column_array = checkAndGetColumn(column.get())) + if (const auto * column_array = checkAndGetColumn(column.get())) { const auto * array_type = checkAndGetDataType(data_type.get()); if (!array_type) - throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot cast array column to column with type {} in function {}", - data_type->getName(), getName()); + throw Exception( + ErrorCodes::LOGICAL_ERROR, + "Cannot cast array column to column with type {} in function {}", + data_type->getName(), + getName()); auto casted_column = castRemoveNullable(column_array->getDataPtr(), array_type->getNestedType()); return ColumnArray::create(casted_column, column_array->getOffsetsPtr()); } - else if (const auto * column_tuple = checkAndGetColumn(column.get())) + if (const auto * column_tuple = checkAndGetColumn(column.get())) { const auto * tuple_type = checkAndGetDataType(data_type.get()); if (!tuple_type) - throw Exception(ErrorCodes::LOGICAL_ERROR, "Cannot cast tuple column to type {} in function {}", - data_type->getName(), getName()); + throw Exception( + ErrorCodes::LOGICAL_ERROR, "Cannot cast tuple column to type {} in function {}", data_type->getName(), getName()); auto columns_number = column_tuple->tupleSize(); Columns columns(columns_number); diff --git a/src/Functions/array/arrayJaccardIndex.cpp b/src/Functions/array/arrayJaccardIndex.cpp index 7db20667888..56a8c66fc8d 100644 --- a/src/Functions/array/arrayJaccardIndex.cpp +++ b/src/Functions/array/arrayJaccardIndex.cpp @@ -100,10 +100,10 @@ public: const ColumnArray & col_const_array = checkAndGetColumn(*col_const->getDataColumnPtr()); return {&col_const_array, true}; } - else if (const ColumnArray * col_non_const_array = checkAndGetColumn(col.column.get())) + if (const ColumnArray * col_non_const_array = checkAndGetColumn(col.column.get())) return {col_non_const_array, false}; - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Argument for function {} must be array but it has type {}.", col.column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Argument for function {} must be array but it has type {}.", col.column->getName(), getName()); }; const auto & [left_array, left_is_const] = cast_to_array(arguments[0]); diff --git a/src/Functions/array/arrayResize.cpp b/src/Functions/array/arrayResize.cpp index fe928f22d38..39680d1311e 100644 --- a/src/Functions/array/arrayResize.cpp +++ b/src/Functions/array/arrayResize.cpp @@ -49,8 +49,8 @@ DataTypePtr FunctionArrayResize::getReturnTypeImpl(const DataTypes & arguments) if (number_of_arguments == 2) return arguments[0]; - else /* if (number_of_arguments == 3) */ - return std::make_shared(getLeastSupertype(DataTypes{array_type->getNestedType(), arguments[2]})); + /* if (number_of_arguments == 3) */ + return std::make_shared(getLeastSupertype(DataTypes{array_type->getNestedType(), arguments[2]})); } ColumnPtr FunctionArrayResize::executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & return_type, size_t input_rows_count) const diff --git a/src/Functions/array/arrayReverse.cpp b/src/Functions/array/arrayReverse.cpp index 654a6c4cebf..9c7849159e9 100644 --- a/src/Functions/array/arrayReverse.cpp +++ b/src/Functions/array/arrayReverse.cpp @@ -158,8 +158,7 @@ bool FunctionArrayReverse::executeNumber(const IColumn & src_data, const ColumnA return true; } - else - return false; + return false; } bool FunctionArrayReverse::executeFixedString(const IColumn & src_data, const ColumnArray::Offsets & src_offsets, IColumn & res_data) @@ -196,8 +195,7 @@ bool FunctionArrayReverse::executeFixedString(const IColumn & src_data, const Co } return true; } - else - return false; + return false; } bool FunctionArrayReverse::executeString(const IColumn & src_data, const ColumnArray::Offsets & src_array_offsets, IColumn & res_data) @@ -242,8 +240,7 @@ bool FunctionArrayReverse::executeString(const IColumn & src_data, const ColumnA return true; } - else - return false; + return false; } diff --git a/src/Functions/array/arraySlice.cpp b/src/Functions/array/arraySlice.cpp index 561986ba23a..fefe819448f 100644 --- a/src/Functions/array/arraySlice.cpp +++ b/src/Functions/array/arraySlice.cpp @@ -105,7 +105,7 @@ public: { return arguments[0].column; } - else if (isColumnConst(*length_column)) + if (isColumnConst(*length_column)) sink = GatherUtils::sliceFromLeftConstantOffsetBounded(*source, 0, length_column->getInt(0)); else { diff --git a/src/Functions/array/arrayZip.cpp b/src/Functions/array/arrayZip.cpp index 2f8c9a3af02..82e57afda1d 100644 --- a/src/Functions/array/arrayZip.cpp +++ b/src/Functions/array/arrayZip.cpp @@ -106,9 +106,8 @@ public: "The argument 1 and argument {} of function {} have different array sizes", unaligned_index + 1, getName()); - else - return ColumnArray::create( - ColumnTuple::create(std::move(tuple_columns)), static_cast(*holders[0]).getOffsetsPtr()); + return ColumnArray::create( + ColumnTuple::create(std::move(tuple_columns)), static_cast(*holders[0]).getOffsetsPtr()); } else return executeUnaligned(holders, tuple_columns, input_rows_count, has_unaligned); diff --git a/src/Functions/array/emptyArrayToSingle.cpp b/src/Functions/array/emptyArrayToSingle.cpp index 5699a4024a1..baaad9d608d 100644 --- a/src/Functions/array/emptyArrayToSingle.cpp +++ b/src/Functions/array/emptyArrayToSingle.cpp @@ -36,11 +36,9 @@ namespace input_rows_count, Array{nested_type->getDefault()}); } - else - return arguments[0].column; + return arguments[0].column; } - else - return nullptr; + return nullptr; } template @@ -97,8 +95,7 @@ namespace return true; } - else - return false; + return false; } @@ -164,8 +161,7 @@ namespace return true; } - else - return false; + return false; } @@ -260,8 +256,7 @@ namespace return true; } - else - return false; + return false; } diff --git a/src/Functions/array/mapOp.cpp b/src/Functions/array/mapOp.cpp index 614b01c2ac8..9112550e869 100644 --- a/src/Functions/array/mapOp.cpp +++ b/src/Functions/array/mapOp.cpp @@ -159,10 +159,9 @@ private: if (arguments[0]->getTypeId() == TypeIndex::Tuple) return getReturnTypeForTuples(arguments); - else if (arguments[0]->getTypeId() == TypeIndex::Map) + if (arguments[0]->getTypeId() == TypeIndex::Map) return getReturnTypeForMaps(arguments); - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "{} only accepts maps", getName()); + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "{} only accepts maps", getName()); } template diff --git a/src/Functions/array/mapPopulateSeries.cpp b/src/Functions/array/mapPopulateSeries.cpp index 0db71ab2cf8..4083678b209 100644 --- a/src/Functions/array/mapPopulateSeries.cpp +++ b/src/Functions/array/mapPopulateSeries.cpp @@ -139,8 +139,7 @@ private: if (key_argument_data_type.isArray()) return std::make_shared(DataTypes{arguments[0], arguments[1]}); - else - return arguments[0]; + return arguments[0]; } template diff --git a/src/Functions/array/range.cpp b/src/Functions/array/range.cpp index f387d30c319..eae1cf5fe45 100644 --- a/src/Functions/array/range.cpp +++ b/src/Functions/array/range.cpp @@ -132,8 +132,7 @@ private: return ColumnArray::create(std::move(data_col), std::move(offsets_col)); } - else - return nullptr; + return nullptr; } template diff --git a/src/Functions/assumeNotNull.cpp b/src/Functions/assumeNotNull.cpp index be9d38f5af3..991fe2296d5 100644 --- a/src/Functions/assumeNotNull.cpp +++ b/src/Functions/assumeNotNull.cpp @@ -56,8 +56,7 @@ public: if (const auto * nullable_col = checkAndGetColumn(&*col)) return nullable_col->getNestedColumnPtr(); - else - return col; + return col; } }; diff --git a/src/Functions/bitShiftLeft.cpp b/src/Functions/bitShiftLeft.cpp index d561430d51f..0eb0d82ef0f 100644 --- a/src/Functions/bitShiftLeft.cpp +++ b/src/Functions/bitShiftLeft.cpp @@ -45,7 +45,7 @@ struct BitShiftLeftImpl const UInt128 bit_limit = static_cast(word_size) * n; if (b < 0 || static_cast(b) > bit_limit) throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "The number of shift positions needs to be a non-negative value and less or equal to the bit width of the value to shift"); - else if (b == bit_limit) + if (b == bit_limit) { // insert default value out_vec.push_back(0); @@ -113,7 +113,7 @@ struct BitShiftLeftImpl const UInt128 bit_limit = static_cast(word_size) * n; if (b < 0 || static_cast(b) > bit_limit) throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "The number of shift positions needs to be a non-negative value and less or equal to the bit width of the value to shift"); - else if (b == bit_limit) + if (b == bit_limit) { // insert default value out_vec.resize_fill(out_vec.size() + n); diff --git a/src/Functions/bitShiftRight.cpp b/src/Functions/bitShiftRight.cpp index 05b8581c792..16032b32f68 100644 --- a/src/Functions/bitShiftRight.cpp +++ b/src/Functions/bitShiftRight.cpp @@ -61,7 +61,7 @@ struct BitShiftRightImpl const UInt128 bit_limit = static_cast(word_size) * n; if (b < 0 || static_cast(b) > bit_limit) throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "The number of shift positions needs to be a non-negative value and less or equal to the bit width of the value to shift"); - else if (b == bit_limit) + if (b == bit_limit) { /// insert default value out_vec.push_back(0); @@ -101,7 +101,7 @@ struct BitShiftRightImpl const UInt128 bit_limit = static_cast(word_size) * n; if (b < 0 || static_cast(b) > bit_limit) throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "The number of shift positions needs to be a non-negative value and less or equal to the bit width of the value to shift"); - else if (b == bit_limit) + if (b == bit_limit) { // insert default value out_vec.resize_fill(out_vec.size() + n); diff --git a/src/Functions/bitSlice.cpp b/src/Functions/bitSlice.cpp index 908c534b228..64060f01e5f 100644 --- a/src/Functions/bitSlice.cpp +++ b/src/Functions/bitSlice.cpp @@ -84,18 +84,17 @@ public: if (const ColumnString * col = checkAndGetColumn(column_string.get())) return executeForSource(column_start, column_length, start_const, length_const, StringSource(*col), input_rows_count); - else if (const ColumnFixedString * col_fixed = checkAndGetColumn(column_string.get())) + if (const ColumnFixedString * col_fixed = checkAndGetColumn(column_string.get())) return executeForSource( column_start, column_length, start_const, length_const, FixedStringSource(*col_fixed), input_rows_count); - else if (const ColumnConst * col_const = checkAndGetColumnConst(column_string.get())) + if (const ColumnConst * col_const = checkAndGetColumnConst(column_string.get())) return executeForSource( column_start, column_length, start_const, length_const, ConstSource(*col_const), input_rows_count); - else if (const ColumnConst * col_const_fixed = checkAndGetColumnConst(column_string.get())) + if (const ColumnConst * col_const_fixed = checkAndGetColumnConst(column_string.get())) return executeForSource( column_start, column_length, start_const, length_const, ConstSource(*col_const_fixed), input_rows_count); - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", arguments[0].column->getName(), getName()); } template diff --git a/src/Functions/checkHyperscanRegexp.cpp b/src/Functions/checkHyperscanRegexp.cpp index d7fb7befc41..0ebee20e60d 100644 --- a/src/Functions/checkHyperscanRegexp.cpp +++ b/src/Functions/checkHyperscanRegexp.cpp @@ -97,7 +97,7 @@ bool SlowWithHyperscanChecker::isSlow(std::string_view regexp) { if (isSlowOneRepeat(regexp)) return true; - else if (isSlowTwoRepeats(regexp)) + if (isSlowTwoRepeats(regexp)) return true; return false; } diff --git a/src/Functions/concat.cpp b/src/Functions/concat.cpp index 5c5e089e740..45f3f4ef5aa 100644 --- a/src/Functions/concat.cpp +++ b/src/Functions/concat.cpp @@ -60,16 +60,15 @@ public: res_data->insertDefault(); return ColumnConst::create(std::move(res_data), input_rows_count); } - else if (arguments.size() == 1) + if (arguments.size() == 1) return arguments[0].column; /// Format function is not proven to be faster for two arguments. /// Actually there is overhead of 2 to 5 extra instructions for each string for checking empty strings in FormatImpl. /// Though, benchmarks are really close, for most examples we saw executeBinary is slightly faster (0-3%). /// For 3 and more arguments FormatStringImpl is much faster (up to 50-60%). - else if (arguments.size() == 2) + if (arguments.size() == 2) return executeBinary(arguments, input_rows_count); - else - return executeFormatImpl(arguments, input_rows_count); + return executeFormatImpl(arguments, input_rows_count); } private: diff --git a/src/Functions/convertCharset.cpp b/src/Functions/convertCharset.cpp index d998e88e7c2..308aea41ac0 100644 --- a/src/Functions/convertCharset.cpp +++ b/src/Functions/convertCharset.cpp @@ -207,8 +207,8 @@ public: convert(charset_from, charset_to, col_from->getChars(), col_from->getOffsets(), col_to->getChars(), col_to->getOffsets(), input_rows_count); return col_to; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column passed as first argument of function {} (must be ColumnString).", getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column passed as first argument of function {} (must be ColumnString).", getName()); } }; diff --git a/src/Functions/countDigits.cpp b/src/Functions/countDigits.cpp index f2712b5b301..d8532636ab6 100644 --- a/src/Functions/countDigits.cpp +++ b/src/Functions/countDigits.cpp @@ -38,8 +38,7 @@ int digits10(T x) { if (x < 10000ULL) return 4; - else - return 5 + (x >= 100000ULL); + return 5 + (x >= 100000ULL); } return 7 + (x >= 10000000ULL); diff --git a/src/Functions/countMatches.h b/src/Functions/countMatches.h index 5f07b936e26..5b8c6be08e6 100644 --- a/src/Functions/countMatches.h +++ b/src/Functions/countMatches.h @@ -61,7 +61,7 @@ public: uint64_t matches_count = countMatches(str, re, matches); return result_type->createColumnConst(input_rows_count, matches_count); } - else if (const ColumnString * col_haystack_string = checkAndGetColumn(col_haystack)) + if (const ColumnString * col_haystack_string = checkAndGetColumn(col_haystack)) { auto col_res = ColumnUInt64::create(); @@ -85,7 +85,7 @@ public: return col_res; } - else if (const ColumnFixedString * col_haystack_fixedstring = checkAndGetColumn(col_haystack)) + if (const ColumnFixedString * col_haystack_fixedstring = checkAndGetColumn(col_haystack)) { auto col_res = ColumnUInt64::create(); @@ -100,8 +100,7 @@ public: return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Could not cast haystack argument to String or FixedString"); + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Could not cast haystack argument to String or FixedString"); } static uint64_t countMatches(std::string_view src, const OptimizedRegularExpression & re, OptimizedRegularExpression::MatchVec & matches) diff --git a/src/Functions/date_trunc.cpp b/src/Functions/date_trunc.cpp index 15d50724506..020a2da5004 100644 --- a/src/Functions/date_trunc.cpp +++ b/src/Functions/date_trunc.cpp @@ -123,19 +123,17 @@ public: return std::make_shared(); if (result_type == ResultType::Date32) return std::make_shared(); - else if (result_type == ResultType::DateTime) + if (result_type == ResultType::DateTime) return std::make_shared(extractTimeZoneNameFromFunctionArguments(arguments, 2, 1, false)); - else - { - size_t scale; - if (datepart_kind == IntervalKind::Kind::Millisecond) - scale = 3; - else if (datepart_kind == IntervalKind::Kind::Microsecond) - scale = 6; - else if (datepart_kind == IntervalKind::Kind::Nanosecond) - scale = 9; - return std::make_shared(scale, extractTimeZoneNameFromFunctionArguments(arguments, 2, 1, false)); - } + + size_t scale; + if (datepart_kind == IntervalKind::Kind::Millisecond) + scale = 3; + else if (datepart_kind == IntervalKind::Kind::Microsecond) + scale = 6; + else if (datepart_kind == IntervalKind::Kind::Nanosecond) + scale = 9; + return std::make_shared(scale, extractTimeZoneNameFromFunctionArguments(arguments, 2, 1, false)); } bool useDefaultImplementationForConstants() const override { return true; } diff --git a/src/Functions/decodeHTMLComponent.cpp b/src/Functions/decodeHTMLComponent.cpp index d36bee534a8..7cdf6413151 100644 --- a/src/Functions/decodeHTMLComponent.cpp +++ b/src/Functions/decodeHTMLComponent.cpp @@ -156,14 +156,14 @@ namespace ++dst_pos; return 1; } - else if (code_point < (1 << 11)) + if (code_point < (1 << 11)) { dst_pos[0] = ((code_point >> 6) & 0x1F) + 0xC0; dst_pos[1] = (code_point & 0x3F) + 0x80; dst_pos += 2; return 2; } - else if (code_point < (1 << 16)) + if (code_point < (1 << 16)) { dst_pos[0] = ((code_point >> 12) & 0x0F) + 0xE0; dst_pos[1] = ((code_point >> 6) & 0x3F) + 0x80; @@ -171,15 +171,13 @@ namespace dst_pos += 3; return 3; } - else - { - dst_pos[0] = ((code_point >> 18) & 0x07) + 0xF0; - dst_pos[1] = ((code_point >> 12) & 0x3F) + 0x80; - dst_pos[2] = ((code_point >> 6) & 0x3F) + 0x80; - dst_pos[3] = (code_point & 0x3F) + 0x80; - dst_pos += 4; - return 4; - } + + dst_pos[0] = ((code_point >> 18) & 0x07) + 0xF0; + dst_pos[1] = ((code_point >> 12) & 0x3F) + 0x80; + dst_pos[2] = ((code_point >> 6) & 0x3F) + 0x80; + dst_pos[3] = (code_point & 0x3F) + 0x80; + dst_pos += 4; + return 4; } [[maybe_unused]] static bool isValidNumericEntity(const char * src, const char * end, uint32_t & code_point) diff --git a/src/Functions/encodeXMLComponent.cpp b/src/Functions/encodeXMLComponent.cpp index a22917838b7..e5e1d12edb1 100644 --- a/src/Functions/encodeXMLComponent.cpp +++ b/src/Functions/encodeXMLComponent.cpp @@ -70,7 +70,7 @@ namespace { break; } - else if (*src_curr_pos == '<') + if (*src_curr_pos == '<') { size_t bytes_to_copy = src_curr_pos - src_prev_pos; memcpySmallAllowReadWriteOverflow15(dst_pos, src_prev_pos, bytes_to_copy); diff --git a/src/Functions/extractTimeZoneFromFunctionArguments.cpp b/src/Functions/extractTimeZoneFromFunctionArguments.cpp index cb8a834ed3b..be3aeee9035 100644 --- a/src/Functions/extractTimeZoneFromFunctionArguments.cpp +++ b/src/Functions/extractTimeZoneFromFunctionArguments.cpp @@ -39,20 +39,18 @@ std::string extractTimeZoneNameFromFunctionArguments(const ColumnsWithTypeAndNam { return extractTimeZoneNameFromColumn(arguments[time_zone_arg_num].column.get(), arguments[time_zone_arg_num].name); } - else - { - if (arguments.size() <= datetime_arg_num) - return {}; - - const auto & dt_arg = arguments[datetime_arg_num].type.get(); - /// If time zone is attached to an argument of type DateTime. - if (const auto * type = checkAndGetDataType(dt_arg)) - return type->hasExplicitTimeZone() ? type->getTimeZone().getTimeZone() : std::string(); - if (const auto * type = checkAndGetDataType(dt_arg)) - return type->hasExplicitTimeZone() ? type->getTimeZone().getTimeZone() : std::string(); + if (arguments.size() <= datetime_arg_num) return {}; - } + + const auto & dt_arg = arguments[datetime_arg_num].type.get(); + /// If time zone is attached to an argument of type DateTime. + if (const auto * type = checkAndGetDataType(dt_arg)) + return type->hasExplicitTimeZone() ? type->getTimeZone().getTimeZone() : std::string(); + if (const auto * type = checkAndGetDataType(dt_arg)) + return type->hasExplicitTimeZone() ? type->getTimeZone().getTimeZone() : std::string(); + + return {}; } const DateLUTImpl & extractTimeZoneFromFunctionArguments(const ColumnsWithTypeAndName & arguments, size_t time_zone_arg_num, size_t datetime_arg_num) @@ -64,20 +62,18 @@ const DateLUTImpl & extractTimeZoneFromFunctionArguments(const ColumnsWithTypeAn throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Provided time zone must be non-empty and be a valid time zone"); return DateLUT::instance(time_zone); } - else - { - if (arguments.size() <= datetime_arg_num) - return DateLUT::instance(); - - const auto & dt_arg = arguments[datetime_arg_num].type.get(); - /// If time zone is attached to an argument of type DateTime. - if (const auto * type = checkAndGetDataType(dt_arg)) - return type->getTimeZone(); - if (const auto * type = checkAndGetDataType(dt_arg)) - return type->getTimeZone(); + if (arguments.size() <= datetime_arg_num) return DateLUT::instance(); - } + + const auto & dt_arg = arguments[datetime_arg_num].type.get(); + /// If time zone is attached to an argument of type DateTime. + if (const auto * type = checkAndGetDataType(dt_arg)) + return type->getTimeZone(); + if (const auto * type = checkAndGetDataType(dt_arg)) + return type->getTimeZone(); + + return DateLUT::instance(); } } diff --git a/src/Functions/filesystem.cpp b/src/Functions/filesystem.cpp index 9b168f3f088..f62c1acae7e 100644 --- a/src/Functions/filesystem.cpp +++ b/src/Functions/filesystem.cpp @@ -82,28 +82,26 @@ public: auto disk = context->getDisk("default"); return DataTypeUInt64().createColumnConst(input_rows_count, Impl::get(disk)); } - else - { - auto col = arguments[0].column; - if (const ColumnString * col_str = checkAndGetColumn(col.get())) - { - auto disk_map = context->getDisksMap(); - auto col_res = ColumnVector::create(col_str->size()); - auto & data = col_res->getData(); - for (size_t i = 0; i < input_rows_count; ++i) - { - auto disk_name = col_str->getDataAt(i).toString(); - if (auto it = disk_map.find(disk_name); it != disk_map.end()) - data[i] = Impl::get(it->second); - else - throw Exception(ErrorCodes::UNKNOWN_DISK, "Unknown disk name {} while execute function {}", disk_name, getName()); - } - return col_res; + auto col = arguments[0].column; + if (const ColumnString * col_str = checkAndGetColumn(col.get())) + { + auto disk_map = context->getDisksMap(); + + auto col_res = ColumnVector::create(col_str->size()); + auto & data = col_res->getData(); + for (size_t i = 0; i < input_rows_count; ++i) + { + auto disk_name = col_str->getDataAt(i).toString(); + if (auto it = disk_map.find(disk_name); it != disk_map.end()) + data[i] = Impl::get(it->second); + else + throw Exception(ErrorCodes::UNKNOWN_DISK, "Unknown disk name {} while execute function {}", disk_name, getName()); } - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + return col_res; } + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } private: diff --git a/src/Functions/formatDateTime.cpp b/src/Functions/formatDateTime.cpp index ae258646015..56910804866 100644 --- a/src/Functions/formatDateTime.cpp +++ b/src/Functions/formatDateTime.cpp @@ -340,8 +340,7 @@ private: dest[0] = '0' + month; return 1; } - else - return writeNumber2(dest, month); + return writeNumber2(dest, month); } static size_t monthOfYearText(char * dest, Time source, bool abbreviate, UInt64, UInt32, const DateLUTImpl & timezone) @@ -434,8 +433,7 @@ private: dest[0] = '0' + hour; return 1; } - else - return writeNumber2(dest, hour); + return writeNumber2(dest, hour); } size_t mysqlHour12(char * dest, Time source, UInt64, UInt32, const DateLUTImpl & timezone) @@ -454,8 +452,7 @@ private: dest[0] = '0' + hour; return 1; } - else - return writeNumber2(dest, hour); + return writeNumber2(dest, hour); } size_t mysqlMinute(char * dest, Time source, UInt64, UInt32, const DateLUTImpl & timezone) @@ -585,11 +582,9 @@ private: auto year = static_cast(ToYearImpl::execute(source, timezone)); if (min_represent_digits == 2) return writeNumberWithPadding(dest, std::abs(year) % 100, 2); - else - { - year = year <= 0 ? std::abs(year - 1) : year; - return writeNumberWithPadding(dest, year, min_represent_digits); - } + + year = year <= 0 ? std::abs(year - 1) : year; + return writeNumberWithPadding(dest, year, min_represent_digits); } static size_t jodaDayOfWeek1Based(size_t min_represent_digits, char * dest, Time source, UInt64, UInt32, const DateLUTImpl & timezone) @@ -613,8 +608,7 @@ private: auto two_digit_year = year % 100; return writeNumberWithPadding(dest, two_digit_year, 2); } - else - return writeNumberWithPadding(dest, year, min_represent_digits); + return writeNumberWithPadding(dest, year, min_represent_digits); } static size_t jodaWeekYear(size_t min_represent_digits, char * dest, Time source, UInt64, UInt32, const DateLUTImpl & timezone) @@ -864,26 +858,30 @@ public: { return castColumn(arguments[0], result_type); } - else - { - if (!castType(arguments[0].type.get(), [&](const auto & type) + + if (!castType( + arguments[0].type.get(), + [&](const auto & type) { using FromDataType = std::decay_t; if (!(res = executeType(arguments, result_type, input_rows_count))) - throw Exception(ErrorCodes::ILLEGAL_COLUMN, + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of function {}, must be Integer, Date, Date32, DateTime or DateTime64.", - arguments[0].column->getName(), getName()); + arguments[0].column->getName(), + getName()); return true; })) - { - if (!((res = executeType(arguments, result_type, input_rows_count)) - || (res = executeType(arguments, result_type, input_rows_count)) - || (res = executeType(arguments, result_type, input_rows_count)) - || (res = executeType(arguments, result_type, input_rows_count)))) - throw Exception(ErrorCodes::ILLEGAL_COLUMN, - "Illegal column {} of function {}, must be Integer or DateTime.", - arguments[0].column->getName(), getName()); - } + { + if (!((res = executeType(arguments, result_type, input_rows_count)) + || (res = executeType(arguments, result_type, input_rows_count)) + || (res = executeType(arguments, result_type, input_rows_count)) + || (res = executeType(arguments, result_type, input_rows_count)))) + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal column {} of function {}, must be Integer or DateTime.", + arguments[0].column->getName(), + getName()); } } else @@ -1587,20 +1585,18 @@ public: Int64 count = numLiteralChars(cur_token + 1, end); if (count == -1) throw Exception(ErrorCodes::BAD_ARGUMENTS, "No closing single quote for literal"); - else + + for (Int64 i = 1; i <= count; i++) { - for (Int64 i = 1; i <= count; i++) - { - Instruction instruction; - std::string_view literal(cur_token + i, 1); - instruction.setJodaFunc(std::bind_front(&Instruction::template jodaLiteral, literal)); - instructions.push_back(std::move(instruction)); - ++reserve_size; - if (*(cur_token + i) == '\'') - i += 1; - } - pos += count + 2; + Instruction instruction; + std::string_view literal(cur_token + i, 1); + instruction.setJodaFunc(std::bind_front(&Instruction::template jodaLiteral, literal)); + instructions.push_back(std::move(instruction)); + ++reserve_size; + if (*(cur_token + i) == '\'') + i += 1; } + pos += count + 2; } } else diff --git a/src/Functions/formatQuery.cpp b/src/Functions/formatQuery.cpp index 42c7a23dbfa..65e2eb36aa9 100644 --- a/src/Functions/formatQuery.cpp +++ b/src/Functions/formatQuery.cpp @@ -68,8 +68,7 @@ public: DataTypePtr string_type = std::make_shared(); if (error_handling == ErrorHandling::Null) return std::make_shared(string_type); - else - return string_type; + return string_type; } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override @@ -87,11 +86,9 @@ public: if (error_handling == ErrorHandling::Null) return ColumnNullable::create(std::move(col_res), std::move(col_null_map)); - else - return col_res; + return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", col_query->getName(), getName()); + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", col_query->getName(), getName()); } private: @@ -140,10 +137,8 @@ private: continue; } - else - { - throw; - } + + throw; } IAST::FormatSettings settings(buf, output_formatting == OutputFormatting::SingleLine, /*hilite*/ false); diff --git a/src/Functions/formatReadableTimeDelta.cpp b/src/Functions/formatReadableTimeDelta.cpp index 96d3a6fd966..82c4809fdff 100644 --- a/src/Functions/formatReadableTimeDelta.cpp +++ b/src/Functions/formatReadableTimeDelta.cpp @@ -320,29 +320,31 @@ private: { if (unit_str.empty()) return default_unit; - else if (unit_str == "years") + if (unit_str == "years") return Years; - else if (unit_str == "months") + if (unit_str == "months") return Months; - else if (unit_str == "days") + if (unit_str == "days") return Days; - else if (unit_str == "hours") + if (unit_str == "hours") return Hours; - else if (unit_str == "minutes") + if (unit_str == "minutes") return Minutes; - else if (unit_str == "seconds") + if (unit_str == "seconds") return Seconds; - else if (unit_str == "milliseconds") + if (unit_str == "milliseconds") return Milliseconds; - else if (unit_str == "microseconds") + if (unit_str == "microseconds") return Microseconds; - else if (unit_str == "nanoseconds") + if (unit_str == "nanoseconds") return Nanoseconds; - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, - "Unexpected value of {} unit argument ({}) for function {}, the only allowed values are:" - " 'nanoseconds', 'microseconds', 'nanoseconds', 'seconds', 'minutes', 'hours', 'days', 'months', 'years'.", - bound_name, unit_str, getName()); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Unexpected value of {} unit argument ({}) for function {}, the only allowed values are:" + " 'nanoseconds', 'microseconds', 'nanoseconds', 'seconds', 'minutes', 'hours', 'days', 'months', 'years'.", + bound_name, + unit_str, + getName()); } }; diff --git a/src/Functions/formatRow.cpp b/src/Functions/formatRow.cpp index 5a67ce158a7..d60e681888d 100644 --- a/src/Functions/formatRow.cpp +++ b/src/Functions/formatRow.cpp @@ -141,8 +141,7 @@ public: std::make_shared>(name_col->getValue(), std::move(arguments_column_names), context), collections::map(arguments, [](const auto & elem) { return elem.type; }), return_type); - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "First argument to {} must be a format name", getName()); + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "First argument to {} must be a format name", getName()); } DataTypePtr getReturnTypeImpl(const DataTypes &) const override { return std::make_shared(); } diff --git a/src/Functions/fromModifiedJulianDay.cpp b/src/Functions/fromModifiedJulianDay.cpp index a1a3102c70e..603b4650013 100644 --- a/src/Functions/fromModifiedJulianDay.cpp +++ b/src/Functions/fromModifiedJulianDay.cpp @@ -179,9 +179,8 @@ namespace DB */ if (WhichDataType(from_type_not_null).isNothing()) // Nullable(Nothing) return std::make_unique>(argument_types, return_type); - else - // Should not happen. - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "The argument of function {} must be integral", getName()); + // Should not happen. + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "The argument of function {} must be integral", getName()); } DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override diff --git a/src/Functions/fuzzBits.cpp b/src/Functions/fuzzBits.cpp index b4aa7e48603..f120719d9f8 100644 --- a/src/Functions/fuzzBits.cpp +++ b/src/Functions/fuzzBits.cpp @@ -144,7 +144,7 @@ public: return col_to; } - else if (const ColumnFixedString * col_in_fixed = checkAndGetColumn(col_in_untyped.get())) + if (const ColumnFixedString * col_in_fixed = checkAndGetColumn(col_in_untyped.get())) { const auto n = col_in_fixed->getN(); const auto col_in_rows = col_in_fixed->size(); @@ -163,20 +163,16 @@ public: if (col_in_rows >= input_rows_count) fuzzBits(ptr_in, ptr_to, chars_to.size(), inverse_probability); else if (col_in_rows != 1) - throw Exception( - ErrorCodes::LOGICAL_ERROR, - "1 != col_in_rows {} < input_rows_count {}", col_in_rows, input_rows_count); + throw Exception(ErrorCodes::LOGICAL_ERROR, "1 != col_in_rows {} < input_rows_count {}", col_in_rows, input_rows_count); else for (size_t i = 0; i < input_rows_count; ++i) fuzzBits(ptr_in, ptr_to + i * n, n, inverse_probability); return col_to; } - else - { - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); - } + + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/geometryConverters.h b/src/Functions/geometryConverters.h index f1156d81f01..c812c58db4e 100644 --- a/src/Functions/geometryConverters.h +++ b/src/Functions/geometryConverters.h @@ -467,21 +467,21 @@ static void callOnGeometryDataType(DataTypePtr type, F && f) /// We should take the name into consideration to avoid ambiguity. /// Because for example both Ring and LineString are resolved to Array(Tuple(Point)). - else if (factory.get("LineString")->equals(*type) && type->getCustomName() && type->getCustomName()->getName() == "LineString") + if (factory.get("LineString")->equals(*type) && type->getCustomName() && type->getCustomName()->getName() == "LineString") return f(ConverterType>()); /// We should take the name into consideration to avoid ambiguity. /// Because for example both MultiLineString and Polygon are resolved to Array(Array(Point)). - else if (factory.get("MultiLineString")->equals(*type) && type->getCustomName() && type->getCustomName()->getName() == "MultiLineString") + if (factory.get("MultiLineString")->equals(*type) && type->getCustomName() && type->getCustomName()->getName() == "MultiLineString") return f(ConverterType>()); /// For backward compatibility if we call this function not on a custom type, we will consider Array(Tuple(Point)) as type Ring. - else if (factory.get("Ring")->equals(*type)) + if (factory.get("Ring")->equals(*type)) return f(ConverterType>()); - else if (factory.get("Polygon")->equals(*type)) + if (factory.get("Polygon")->equals(*type)) return f(ConverterType>()); - else if (factory.get("MultiPolygon")->equals(*type)) + if (factory.get("MultiPolygon")->equals(*type)) return f(ConverterType>()); throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown geometry type {}", type->getName()); } diff --git a/src/Functions/getScalar.cpp b/src/Functions/getScalar.cpp index 001fc4bad47..0e94a44bf22 100644 --- a/src/Functions/getScalar.cpp +++ b/src/Functions/getScalar.cpp @@ -88,7 +88,7 @@ public: { if (auto block = context_->tryGetSpecialScalar(Scalar::scalar_name)) return block->getByPosition(0); - else if (context_->hasQueryContext()) + if (context_->hasQueryContext()) { if (context_->getQueryContext()->hasScalar(Scalar::scalar_name)) return context_->getQueryContext()->getScalar(Scalar::scalar_name).getByPosition(0); diff --git a/src/Functions/getSizeOfEnumType.cpp b/src/Functions/getSizeOfEnumType.cpp index 7eabcb5150a..12a26b5bf0f 100644 --- a/src/Functions/getSizeOfEnumType.cpp +++ b/src/Functions/getSizeOfEnumType.cpp @@ -45,7 +45,7 @@ public: if (which.isEnum8()) return std::make_shared(); - else if (which.isEnum16()) + if (which.isEnum16()) return std::make_shared(); throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "The argument for function {} must be Enum", getName()); @@ -67,10 +67,9 @@ private: { if (const auto * type8 = checkAndGetDataType(data_type.get())) return DataTypeUInt8().createColumnConst(input_rows_count, type8->getValues().size()); - else if (const auto * type16 = checkAndGetDataType(data_type.get())) + if (const auto * type16 = checkAndGetDataType(data_type.get())) return DataTypeUInt16().createColumnConst(input_rows_count, type16->getValues().size()); - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "The argument for function {} must be Enum", getName()); + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "The argument for function {} must be Enum", getName()); } }; diff --git a/src/Functions/globalVariable.cpp b/src/Functions/globalVariable.cpp index 9ec7e82bf6b..ee455ae11b2 100644 --- a/src/Functions/globalVariable.cpp +++ b/src/Functions/globalVariable.cpp @@ -56,8 +56,7 @@ public: auto variable = global_variable_map.find(Poco::toLower(variable_name)); if (variable == global_variable_map.end()) return std::make_shared(); - else - return variable->second.type; + return variable->second.type; } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override diff --git a/src/Functions/greatCircleDistance.cpp b/src/Functions/greatCircleDistance.cpp index 0aca78f0d3f..0385790ac7c 100644 --- a/src/Functions/greatCircleDistance.cpp +++ b/src/Functions/greatCircleDistance.cpp @@ -208,21 +208,18 @@ T distance(T lon1deg, T lat1deg, T lon2deg, T lat2deg) /// Metric on a tangent plane: it differs from Euclidean metric only by scale of coordinates. return std::sqrt(k_lat * lat_diff * lat_diff + k_lon * lon_diff * lon_diff); } + /// Points are too far away: use Haversine. + + static constexpr T RAD_IN_DEG = T(PI / 180.0); + static constexpr T RAD_IN_DEG_HALF = T(PI / 360.0); + + T a = sqr(impl.fastSin(lat_diff * RAD_IN_DEG_HALF)) + + impl.fastCos(lat1deg * RAD_IN_DEG) * impl.fastCos(lat2deg * RAD_IN_DEG) * sqr(impl.fastSin(lon_diff * RAD_IN_DEG_HALF)); + + if constexpr (method == Method::SPHERE_DEGREES) + return (T(360.0) / T(PI)) * impl.fastAsinSqrt(a); else - { - /// Points are too far away: use Haversine. - - static constexpr T RAD_IN_DEG = T(PI / 180.0); - static constexpr T RAD_IN_DEG_HALF = T(PI / 360.0); - - T a = sqr(impl.fastSin(lat_diff * RAD_IN_DEG_HALF)) - + impl.fastCos(lat1deg * RAD_IN_DEG) * impl.fastCos(lat2deg * RAD_IN_DEG) * sqr(impl.fastSin(lon_diff * RAD_IN_DEG_HALF)); - - if constexpr (method == Method::SPHERE_DEGREES) - return (T(360.0) / T(PI)) * impl.fastAsinSqrt(a); - else - return T(EARTH_DIAMETER) * impl.fastAsinSqrt(a); - } + return T(EARTH_DIAMETER) * impl.fastAsinSqrt(a); } } @@ -272,8 +269,8 @@ private: if (has_float64 && !always_float32) return std::make_shared(); - else - return std::make_shared(); + + return std::make_shared(); } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override diff --git a/src/Functions/if.cpp b/src/Functions/if.cpp index 73fd9f13db7..e03b27b3c39 100644 --- a/src/Functions/if.cpp +++ b/src/Functions/if.cpp @@ -312,7 +312,7 @@ private: return NumIfImpl::vectorVector( cond_col->getData(), col_left->getData(), col_right_vec->getData(), scale); } - else if (const auto * col_right_const = checkAndGetColumnConst(col_right_untyped)) + if (const auto * col_right_const = checkAndGetColumnConst(col_right_untyped)) { return NumIfImpl::vectorConstant( cond_col->getData(), col_left->getData(), col_right_const->template getValue(), scale); @@ -344,7 +344,7 @@ private: return NumIfImpl::constantVector( cond_col->getData(), col_left->template getValue(), col_right_vec->getData(), scale); } - else if (const auto * col_right_const = checkAndGetColumnConst(col_right_untyped)) + if (const auto * col_right_const = checkAndGetColumnConst(col_right_untyped)) { return NumIfImpl::constantConstant( cond_col->getData(), col_left->template getValue(), col_right_const->template getValue(), scale); @@ -389,7 +389,7 @@ private: return res; } - else if (const auto * col_right_const_array = checkAndGetColumnConst(col_right_untyped)) + if (const auto * col_right_const_array = checkAndGetColumnConst(col_right_untyped)) { const ColumnArray * col_right_const_array_data = checkAndGetColumn(&col_right_const_array->getDataColumn()); if (!checkColumn(&col_right_const_array_data->getData())) @@ -447,7 +447,7 @@ private: return res; } - else if (const auto * col_right_const_array = checkAndGetColumnConst(col_right_untyped)) + if (const auto * col_right_const_array = checkAndGetColumnConst(col_right_untyped)) { const ColumnArray * col_right_const_array_data = checkAndGetColumn(&col_right_const_array->getDataColumn()); if (!checkColumn(&col_right_const_array_data->getData())) @@ -874,7 +874,7 @@ private: if (cond_is_true) return castColumn(column1, result_type); - else if (cond_is_false || cond_is_null) + if (cond_is_false || cond_is_null) return castColumn(column2, result_type); if (const auto * nullable = checkAndGetColumn(&*not_const_condition)) @@ -934,7 +934,7 @@ private: /// Nullable cannot contain Nullable return nullable->getNestedColumnPtr(); } - else if (const auto * column_const = checkAndGetColumn(&*column)) + if (const auto * column_const = checkAndGetColumn(&*column)) { /// Save Constant, but remove Nullable return ColumnConst::create(recursiveGetNestedColumnWithoutNullable(column_const->getDataColumnPtr()), column->size()); @@ -1049,29 +1049,30 @@ private: assert_cast(*result_column).applyNullMap(assert_cast(*arg_cond.column)); return result_column; } - else if (auto * variant_column = typeid_cast(result_column.get())) + if (auto * variant_column = typeid_cast(result_column.get())) { variant_column->applyNullMap(assert_cast(*arg_cond.column).getData()); return result_column; } - else if (auto * dynamic_column = typeid_cast(result_column.get())) + if (auto * dynamic_column = typeid_cast(result_column.get())) { dynamic_column->applyNullMap(assert_cast(*arg_cond.column).getData()); return result_column; } - else - return ColumnNullable::create(materializeColumnIfConst(result_column), arg_cond.column); + return ColumnNullable::create(materializeColumnIfConst(result_column), arg_cond.column); } - else if (cond_const_col) + if (cond_const_col) { if (cond_const_col->getValue()) return result_type->createColumn()->cloneResized(input_rows_count); - else - return makeNullableColumnIfNot(arg_else_column); + return makeNullableColumnIfNot(arg_else_column); } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}. " - "Must be ColumnUInt8 or ColumnConstUInt8.", arg_cond.column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal column {} of first argument of function {}. " + "Must be ColumnUInt8 or ColumnConstUInt8.", + arg_cond.column->getName(), + getName()); } /// If else is NULL, we create Nullable column with null mask OR-ed with negated condition. @@ -1095,41 +1096,41 @@ private: assert_cast(*result_column).applyNegatedNullMap(assert_cast(*arg_cond.column)); return result_column; } - else if (auto * variant_column = typeid_cast(result_column.get())) + if (auto * variant_column = typeid_cast(result_column.get())) { variant_column->applyNegatedNullMap(assert_cast(*arg_cond.column).getData()); return result_column; } - else if (auto * dynamic_column = typeid_cast(result_column.get())) + if (auto * dynamic_column = typeid_cast(result_column.get())) { dynamic_column->applyNegatedNullMap(assert_cast(*arg_cond.column).getData()); return result_column; } - else - { - size_t size = input_rows_count; - const auto & null_map_data = cond_col->getData(); - auto negated_null_map = ColumnUInt8::create(); - auto & negated_null_map_data = negated_null_map->getData(); - negated_null_map_data.resize(size); + size_t size = input_rows_count; + const auto & null_map_data = cond_col->getData(); - for (size_t i = 0; i < size; ++i) - negated_null_map_data[i] = !null_map_data[i]; + auto negated_null_map = ColumnUInt8::create(); + auto & negated_null_map_data = negated_null_map->getData(); + negated_null_map_data.resize(size); - return ColumnNullable::create(materializeColumnIfConst(result_column), std::move(negated_null_map)); - } + for (size_t i = 0; i < size; ++i) + negated_null_map_data[i] = !null_map_data[i]; + + return ColumnNullable::create(materializeColumnIfConst(result_column), std::move(negated_null_map)); } - else if (cond_const_col) + if (cond_const_col) { if (cond_const_col->getValue()) return makeNullableColumnIfNot(arg_then_column); - else - return result_type->createColumn()->cloneResized(input_rows_count); + return result_type->createColumn()->cloneResized(input_rows_count); } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}. " - "Must be ColumnUInt8 or ColumnConstUInt8.", arg_cond.column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal column {} of first argument of function {}. " + "Must be ColumnUInt8 or ColumnConstUInt8.", + arg_cond.column->getName(), + getName()); } return nullptr; @@ -1231,8 +1232,7 @@ public: const ColumnWithTypeAndName & arg = value ? arg_then : arg_else; if (arg.type->equals(*result_type)) return arg.column; - else - return castColumn(arg, result_type); + return castColumn(arg, result_type); } if (!cond_col) diff --git a/src/Functions/isDecimalOverflow.cpp b/src/Functions/isDecimalOverflow.cpp index 93485b32d03..04d95fdab32 100644 --- a/src/Functions/isDecimalOverflow.cpp +++ b/src/Functions/isDecimalOverflow.cpp @@ -100,7 +100,7 @@ public: result_column->getData().resize_fill(input_rows_count, res_value); return true; } - else if (const ColVecType * col_vec = checkAndGetColumn(src_column.column.get())) + if (const ColVecType * col_vec = checkAndGetColumn(src_column.column.get())) { execute(*col_vec, *result_column, input_rows_count, precision); return true; diff --git a/src/Functions/isIPAddressContainedIn.cpp b/src/Functions/isIPAddressContainedIn.cpp index abbcb0a5e37..3ef2f5fbfb0 100644 --- a/src/Functions/isIPAddressContainedIn.cpp +++ b/src/Functions/isIPAddressContainedIn.cpp @@ -131,16 +131,12 @@ namespace DB { if (const auto * col_cidr_const = checkAndGetAnyColumnConst(col_cidr)) return executeImpl(*col_addr_const, *col_cidr_const, input_rows_count); - else - return executeImpl(*col_addr_const, *col_cidr, input_rows_count); - } - else - { - if (const auto * col_cidr_const = checkAndGetAnyColumnConst(col_cidr)) - return executeImpl(*col_addr, *col_cidr_const, input_rows_count); - else - return executeImpl(*col_addr, *col_cidr, input_rows_count); + return executeImpl(*col_addr_const, *col_cidr, input_rows_count); } + + if (const auto * col_cidr_const = checkAndGetAnyColumnConst(col_cidr)) + return executeImpl(*col_addr, *col_cidr_const, input_rows_count); + return executeImpl(*col_addr, *col_cidr, input_rows_count); } DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override diff --git a/src/Functions/isNotNull.cpp b/src/Functions/isNotNull.cpp index 3fe046d7d1b..4af2ba8b987 100644 --- a/src/Functions/isNotNull.cpp +++ b/src/Functions/isNotNull.cpp @@ -105,11 +105,9 @@ public: vector(src_data, res_data); return res_column; } - else - { - /// Since no element is nullable, return a constant one. - return DataTypeUInt8().createColumnConst(elem.column->size(), 1u); - } + + /// Since no element is nullable, return a constant one. + return DataTypeUInt8().createColumnConst(elem.column->size(), 1u); } private: diff --git a/src/Functions/isNull.cpp b/src/Functions/isNull.cpp index 52e26777f7d..f66c5c0f7ab 100644 --- a/src/Functions/isNull.cpp +++ b/src/Functions/isNull.cpp @@ -101,12 +101,10 @@ public: /// Merely return the embedded null map. return nullable->getNullMapColumnPtr(); } - else - { - /// Since no element is nullable, return a zero-constant column representing - /// a zero-filled null map. - return DataTypeUInt8().createColumnConst(elem.column->size(), 0u); - } + + /// Since no element is nullable, return a zero-constant column representing + /// a zero-filled null map. + return DataTypeUInt8().createColumnConst(elem.column->size(), 0u); } private: diff --git a/src/Functions/keyvaluepair/ArgumentExtractor.cpp b/src/Functions/keyvaluepair/ArgumentExtractor.cpp index 39af80cb561..7d13699ef71 100644 --- a/src/Functions/keyvaluepair/ArgumentExtractor.cpp +++ b/src/Functions/keyvaluepair/ArgumentExtractor.cpp @@ -86,7 +86,7 @@ ArgumentExtractor::CharArgument ArgumentExtractor::extractSingleCharacter(const { return {}; } - else if (view.size() == 1u) + if (view.size() == 1u) { return view.front(); } diff --git a/src/Functions/keyvaluepair/impl/StateHandlerImpl.h b/src/Functions/keyvaluepair/impl/StateHandlerImpl.h index cf31d30b9dc..bdcdfdf0aff 100644 --- a/src/Functions/keyvaluepair/impl/StateHandlerImpl.h +++ b/src/Functions/keyvaluepair/impl/StateHandlerImpl.h @@ -59,10 +59,8 @@ public: // +1 to skip quoting character return {character_position + 1u, State::READING_QUOTED_KEY}; } - else - { - return {character_position, State::READING_KEY}; - } + + return {character_position, State::READING_KEY}; } return {file.size(), State::END}; diff --git a/src/Functions/minSampleSize.cpp b/src/Functions/minSampleSize.cpp index f37b030c85a..a7bce508aa0 100644 --- a/src/Functions/minSampleSize.cpp +++ b/src/Functions/minSampleSize.cpp @@ -197,14 +197,12 @@ struct ConversionImpl const Float64 left_value = col_p1_const->template getValue(); return process(arguments, &left_value, input_rows_count); } - else if (const ColumnVector * const col_p1 = checkAndGetColumn>(first_argument_column.get())) + if (const ColumnVector * const col_p1 = checkAndGetColumn>(first_argument_column.get())) { return process(arguments, col_p1->getData().data(), input_rows_count); } - else - { - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "The first argument of function {} must be a float.", name); - } + + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "The first argument of function {} must be a float.", name); } template diff --git a/src/Functions/neighbor.cpp b/src/Functions/neighbor.cpp index 74164218b15..da9192dffce 100644 --- a/src/Functions/neighbor.cpp +++ b/src/Functions/neighbor.cpp @@ -88,9 +88,12 @@ public: if (!isInteger(arguments[1])) throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal type {} of second argument of function {} - should be an integer", arguments[1]->getName(), getName()); - else if (arguments[1]->isNullable()) - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Illegal type {} of second argument of function {} - can not be Nullable", arguments[1]->getName(), getName()); + if (arguments[1]->isNullable()) + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal type {} of second argument of function {} - can not be Nullable", + arguments[1]->getName(), + getName()); // check that default value column has supertype with first argument if (number_of_arguments == 3) @@ -177,43 +180,39 @@ public: ? ColumnConst::create(source_column_casted, input_rows_count) : source_column_casted; } - else if (offset > 0) + if (offset > 0) { insert_range_from(source_is_constant, source_column_casted, offset, static_cast(input_rows_count) - offset); insert_range_from(default_is_constant, default_column_casted, static_cast(input_rows_count) - offset, offset); return result_column; } - else - { - insert_range_from(default_is_constant, default_column_casted, 0, -offset); - insert_range_from(source_is_constant, source_column_casted, 0, static_cast(input_rows_count) + offset); - return result_column; - } - } - else - { - auto result_column = result_type->createColumn(); - - for (size_t row = 0; row < input_rows_count; ++row) - { - Int64 offset = offset_column->getInt(row); - - /// Protection from possible overflow. - if (unlikely(offset > (1 << 30) || offset < -(1 << 30))) - throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Too large offset: {} in function {}", offset, getName()); - - Int64 src_idx = row + offset; - - if (src_idx >= 0 && src_idx < static_cast(input_rows_count)) - result_column->insertFrom(*source_column_casted, source_is_constant ? 0 : src_idx); - else if (has_defaults) - result_column->insertFrom(*default_column_casted, default_is_constant ? 0 : row); - else - result_column->insertDefault(); - } + insert_range_from(default_is_constant, default_column_casted, 0, -offset); + insert_range_from(source_is_constant, source_column_casted, 0, static_cast(input_rows_count) + offset); return result_column; } + + auto result_column = result_type->createColumn(); + + for (size_t row = 0; row < input_rows_count; ++row) + { + Int64 offset = offset_column->getInt(row); + + /// Protection from possible overflow. + if (unlikely(offset > (1 << 30) || offset < -(1 << 30))) + throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Too large offset: {} in function {}", offset, getName()); + + Int64 src_idx = row + offset; + + if (src_idx >= 0 && src_idx < static_cast(input_rows_count)) + result_column->insertFrom(*source_column_casted, source_is_constant ? 0 : src_idx); + else if (has_defaults) + result_column->insertFrom(*default_column_casted, default_is_constant ? 0 : row); + else + result_column->insertDefault(); + } + + return result_column; } }; diff --git a/src/Functions/normalizedQueryHash.cpp b/src/Functions/normalizedQueryHash.cpp index 3dbe3ff9847..d4f0c67f65a 100644 --- a/src/Functions/normalizedQueryHash.cpp +++ b/src/Functions/normalizedQueryHash.cpp @@ -88,9 +88,8 @@ public: Impl::vector(col->getChars(), col->getOffsets(), vec_res, input_rows_count); return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/overlay.cpp b/src/Functions/overlay.cpp index eddb7590cab..34c4a841cb2 100644 --- a/src/Functions/overlay.cpp +++ b/src/Functions/overlay.cpp @@ -194,16 +194,12 @@ private: { if (static_cast(offset) > input_size + 1) return input_size; - else - return offset - 1; - } - else - { - if (input_size < -static_cast(offset)) - return 0; - else - return input_size + offset; + return offset - 1; } + + if (input_size < -static_cast(offset)) + return 0; + return input_size + offset; } /// get character count of a slice [data, data+bytes) diff --git a/src/Functions/parseDateTime.cpp b/src/Functions/parseDateTime.cpp index 2dd6db94cfb..a4b23745308 100644 --- a/src/Functions/parseDateTime.cpp +++ b/src/Functions/parseDateTime.cpp @@ -484,13 +484,12 @@ namespace // negative date: start off at 4 and cycle downwards return (7 - ((-days_since_epoch + 3) % 7)); } - else - { - // positive date: start off at 4 and cycle upwards - return ((days_since_epoch + 3) % 7) + 1; - } + + // positive date: start off at 4 and cycle upwards + return ((days_since_epoch + 3) % 7) + 1; } + /// NOLINTBEGIN(readability-else-after-return) [[nodiscard]] static Int32OrError daysSinceEpochFromWeekDate(int32_t week_year_, int32_t week_of_year_, int32_t day_of_week_) { @@ -602,8 +601,7 @@ namespace DataTypePtr date_type = std::make_shared(time_zone_name); if (error_handling == ErrorHandling::Null) return std::make_shared(date_type); - else - return date_type; + return date_type; } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & /*result_type*/, size_t input_rows_count) const override @@ -749,8 +747,7 @@ namespace { if (func) return "func:" + func_name + ",fragment:" + fragment; - else - return "literal:" + literal + ",fragment:" + fragment; + return "literal:" + literal + ",fragment:" + fragment; } [[nodiscard]] @@ -758,21 +755,19 @@ namespace { if (func) return func(cur, end, fragment, date); - else - { - /// literal: - RETURN_ERROR_IF_FAILED(checkSpace(cur, end, literal.size(), "insufficient space to parse literal", fragment)) - if (std::string_view(cur, literal.size()) != literal) - RETURN_ERROR( - ErrorCodes::CANNOT_PARSE_DATETIME, - "Unable to parse fragment {} from {} because literal {} is expected but {} provided", - fragment, - std::string_view(cur, end - cur), - literal, - std::string_view(cur, literal.size())) - cur += literal.size(); - return cur; - } + + /// literal: + RETURN_ERROR_IF_FAILED(checkSpace(cur, end, literal.size(), "insufficient space to parse literal", fragment)) + if (std::string_view(cur, literal.size()) != literal) + RETURN_ERROR( + ErrorCodes::CANNOT_PARSE_DATETIME, + "Unable to parse fragment {} from {} because literal {} is expected but {} provided", + fragment, + std::string_view(cur, end - cur), + literal, + std::string_view(cur, literal.size())) + cur += literal.size(); + return cur; } template @@ -1631,6 +1626,7 @@ namespace return cur; } }; + /// NOLINTEND(readability-else-after-return) std::vector parseFormat(const String & format) const { @@ -1932,16 +1928,14 @@ namespace Int64 count = numLiteralChars(cur_token + 1, end); if (count == -1) throw Exception(ErrorCodes::BAD_ARGUMENTS, "No closing single quote for literal"); - else + + for (Int64 i = 1; i <= count; i++) { - for (Int64 i = 1; i <= count; i++) - { - instructions.emplace_back(String(cur_token + i, 1)); - if (*(cur_token + i) == '\'') - i += 1; - } - pos += count + 2; + instructions.emplace_back(String(cur_token + i, 1)); + if (*(cur_token + i) == '\'') + i += 1; } + pos += count + 2; } } else diff --git a/src/Functions/parseReadableSize.cpp b/src/Functions/parseReadableSize.cpp index 4f6afb939a5..9746ab46773 100644 --- a/src/Functions/parseReadableSize.cpp +++ b/src/Functions/parseReadableSize.cpp @@ -172,23 +172,15 @@ private: value ); } - else if (std::isnan(base) || !std::isfinite(base)) + if (std::isnan(base) || !std::isfinite(base)) { throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "Invalid expression for function {} - Invalid numeric component: {}", - getName(), - base - ); + ErrorCodes::BAD_ARGUMENTS, "Invalid expression for function {} - Invalid numeric component: {}", getName(), base); } - else if (base < 0) + if (base < 0) { throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "Invalid expression for function {} - Negative sizes are not allowed ({})", - getName(), - base - ); + ErrorCodes::BAD_ARGUMENTS, "Invalid expression for function {} - Negative sizes are not allowed ({})", getName(), base); } skipWhitespaceIfAny(buf); @@ -206,14 +198,13 @@ private: unit ); } - else if (!buf.eof()) + if (!buf.eof()) { throw Exception( ErrorCodes::UNEXPECTED_DATA_AFTER_PARSED_VALUE, "Invalid expression for function {} - Found trailing characters after readable size string (\"{}\")", getName(), - value - ); + value); } Float64 num_bytes_with_decimals = base * iter->second; diff --git a/src/Functions/pointInEllipses.cpp b/src/Functions/pointInEllipses.cpp index ac7a8cc4204..dc438792ef1 100644 --- a/src/Functions/pointInEllipses.cpp +++ b/src/Functions/pointInEllipses.cpp @@ -147,19 +147,23 @@ private: return dst; } - else if (const_cnt == 2) + if (const_cnt == 2) { - const auto * col_const_x = assert_cast (col_x); - const auto * col_const_y = assert_cast (col_y); + const auto * col_const_x = assert_cast(col_x); + const auto * col_const_y = assert_cast(col_y); size_t start_index = 0; - UInt8 res = isPointInEllipses(col_const_x->getValue(), col_const_y->getValue(), ellipses.data(), ellipses_count, start_index); + UInt8 res = isPointInEllipses( + col_const_x->getValue(), col_const_y->getValue(), ellipses.data(), ellipses_count, start_index); return DataTypeUInt8().createColumnConst(input_rows_count, res); } - else - { - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Illegal types {}, {} of arguments 1, 2 of function {}. " - "Both must be either const or vector", col_x->getName(), col_y->getName(), getName()); - } + + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Illegal types {}, {} of arguments 1, 2 of function {}. " + "Both must be either const or vector", + col_x->getName(), + col_y->getName(), + getName()); } static bool isPointInEllipses(Float64 x, Float64 y, const Ellipse * ellipses, size_t ellipses_count, size_t & start_index) diff --git a/src/Functions/pointInPolygon.cpp b/src/Functions/pointInPolygon.cpp index 909fc7a1793..b157334d07a 100644 --- a/src/Functions/pointInPolygon.cpp +++ b/src/Functions/pointInPolygon.cpp @@ -208,72 +208,56 @@ public: bool is_in = impl->contains(tuple_columns[0]->getFloat64(0), tuple_columns[1]->getFloat64(0)); return result_type->createColumnConst(input_rows_count, is_in); } - else + + return pointInPolygon(*tuple_columns[0], *tuple_columns[1], *impl); + } + + if (arguments.size() != 2) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Multi-argument version of function {} works only with const polygon", getName()); + + auto res_column = ColumnVector::create(input_rows_count); + auto & data = res_column->getData(); + + /// A polygon, possibly with holes, is represented by 2d array: + /// [[(outer_x_1, outer_y_1, ...)], [(hole1_x_1, hole1_y_1), ...], ...] + /// + /// Or, a polygon without holes can be represented by 1d array: + /// [(outer_x_1, outer_y_1, ...)] + + if (isTwoDimensionalArray(*arguments[1].type)) + { + /// We cast everything to Float64 in advance (in batch fashion) + /// to avoid casting with virtual calls in a loop. + /// Note that if the type is already Float64, the operation in noop. + + ColumnPtr polygon_column_float64 = castColumn( + arguments[1], + std::make_shared(std::make_shared( + std::make_shared(DataTypes{std::make_shared(), std::make_shared()})))); + + for (size_t i = 0; i < input_rows_count; ++i) { - return pointInPolygon(*tuple_columns[0], *tuple_columns[1], *impl); + size_t point_index = point_is_const ? 0 : i; + data[i] = isInsidePolygonWithHoles( + tuple_columns[0]->getFloat64(point_index), tuple_columns[1]->getFloat64(point_index), *polygon_column_float64, i); } } else { - if (arguments.size() != 2) - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Multi-argument version of function {} works only with const polygon", - getName()); + ColumnPtr polygon_column_float64 = castColumn( + arguments[1], + std::make_shared( + std::make_shared(DataTypes{std::make_shared(), std::make_shared()}))); - auto res_column = ColumnVector::create(input_rows_count); - auto & data = res_column->getData(); - - /// A polygon, possibly with holes, is represented by 2d array: - /// [[(outer_x_1, outer_y_1, ...)], [(hole1_x_1, hole1_y_1), ...], ...] - /// - /// Or, a polygon without holes can be represented by 1d array: - /// [(outer_x_1, outer_y_1, ...)] - - if (isTwoDimensionalArray(*arguments[1].type)) + for (size_t i = 0; i < input_rows_count; ++i) { - /// We cast everything to Float64 in advance (in batch fashion) - /// to avoid casting with virtual calls in a loop. - /// Note that if the type is already Float64, the operation in noop. - - ColumnPtr polygon_column_float64 = castColumn( - arguments[1], - std::make_shared( - std::make_shared( - std::make_shared(DataTypes{ - std::make_shared(), - std::make_shared()})))); - - for (size_t i = 0; i < input_rows_count; ++i) - { - size_t point_index = point_is_const ? 0 : i; - data[i] = isInsidePolygonWithHoles( - tuple_columns[0]->getFloat64(point_index), - tuple_columns[1]->getFloat64(point_index), - *polygon_column_float64, - i); - } + size_t point_index = point_is_const ? 0 : i; + data[i] = isInsidePolygonWithoutHoles( + tuple_columns[0]->getFloat64(point_index), tuple_columns[1]->getFloat64(point_index), *polygon_column_float64, i); } - else - { - ColumnPtr polygon_column_float64 = castColumn( - arguments[1], - std::make_shared( - std::make_shared(DataTypes{ - std::make_shared(), - std::make_shared()}))); - - for (size_t i = 0; i < input_rows_count; ++i) - { - size_t point_index = point_is_const ? 0 : i; - data[i] = isInsidePolygonWithoutHoles( - tuple_columns[0]->getFloat64(point_index), - tuple_columns[1]->getFloat64(point_index), - *polygon_column_float64, - i); - } - } - - return res_column; } + + return res_column; } private: diff --git a/src/Functions/printf.cpp b/src/Functions/printf.cpp index afacf164a00..fd76955159c 100644 --- a/src/Functions/printf.cpp +++ b/src/Functions/printf.cpp @@ -44,10 +44,9 @@ private: { if (is_literal) return executeLiteral(format); - else if (isColumnConst(*input.column)) + if (isColumnConst(*input.column)) return executeConstant(input); - else - return executeNonconstant(input); + return executeNonconstant(input); } private: @@ -143,19 +142,17 @@ private: { return {std::move(res_col), std::make_shared(), arg.name}; } - else if ( - which.isStringOrFixedString() + if (which.isStringOrFixedString() && (executeString(*arg.column, res_chars, res_offsets) || executeString(*arg.column, res_chars, res_offsets))) { return {std::move(res_col), std::make_shared(), arg.name}; } - else - throw Exception( - ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "The argument type of function {} is {}, but native numeric or string type is expected", - FunctionPrintf::name, - arg.type->getName()); + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "The argument type of function {} is {}, but native numeric or string type is expected", + FunctionPrintf::name, + arg.type->getName()); } }; @@ -235,14 +232,13 @@ public: instruction.format, getName(), e.what()); - else - throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "Bad format {} in function {} with {} as input argument, reason: {}", - instructions[i].format, - getName(), - instruction.input.dumpStructure(), - e.what()); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Bad format {} in function {} with {} as input argument, reason: {}", + instructions[i].format, + getName(), + instruction.input.dumpStructure(), + e.what()); } } diff --git a/src/Functions/repeat.cpp b/src/Functions/repeat.cpp index c001959b465..4c7882a3e31 100644 --- a/src/Functions/repeat.cpp +++ b/src/Functions/repeat.cpp @@ -234,16 +234,19 @@ public: return col_res; } - else if (castType(arguments[1].type.get(), [&](const auto & type) - { - using DataType = std::decay_t; - using T = typename DataType::FieldType; - const ColumnVector & column = checkAndGetColumn>(*col_num); - auto col_res = ColumnString::create(); - RepeatImpl::vectorStrVectorRepeat(col->getChars(), col->getOffsets(), col_res->getChars(), col_res->getOffsets(), column.getData()); - res = std::move(col_res); - return true; - })) + if (castType( + arguments[1].type.get(), + [&](const auto & type) + { + using DataType = std::decay_t; + using T = typename DataType::FieldType; + const ColumnVector & column = checkAndGetColumn>(*col_num); + auto col_res = ColumnString::create(); + RepeatImpl::vectorStrVectorRepeat( + col->getChars(), col->getOffsets(), col_res->getChars(), col_res->getOffsets(), column.getData()); + res = std::move(col_res); + return true; + })) { return res; } diff --git a/src/Functions/reverse.cpp b/src/Functions/reverse.cpp index 94b6634ffbd..119bc614098 100644 --- a/src/Functions/reverse.cpp +++ b/src/Functions/reverse.cpp @@ -64,15 +64,14 @@ public: ReverseImpl::vector(col->getChars(), col->getOffsets(), col_res->getChars(), col_res->getOffsets(), input_rows_count); return col_res; } - else if (const ColumnFixedString * col_fixed = checkAndGetColumn(column.get())) + if (const ColumnFixedString * col_fixed = checkAndGetColumn(column.get())) { auto col_res = ColumnFixedString::create(col_fixed->getN()); ReverseImpl::vectorFixed(col_fixed->getChars(), col_fixed->getN(), col_res->getChars(), input_rows_count); return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of argument of function {}", arguments[0].column->getName(), getName()); } }; @@ -93,11 +92,10 @@ public: { if (isArray(arguments.at(0).type)) return FunctionFactory::instance().getImpl("arrayReverse", context)->build(arguments); - else - return std::make_unique( - FunctionReverse::create(context), - collections::map(arguments, [](const auto & elem) { return elem.type; }), - return_type); + return std::make_unique( + FunctionReverse::create(context), + collections::map(arguments, [](const auto & elem) { return elem.type; }), + return_type); } DataTypePtr getReturnTypeImpl(const DataTypes & arguments) const override diff --git a/src/Functions/runningDifference.h b/src/Functions/runningDifference.h index e8143c55c27..1f63664e4cc 100644 --- a/src/Functions/runningDifference.h +++ b/src/Functions/runningDifference.h @@ -226,8 +226,7 @@ public: if (null_map_column) return ColumnNullable::create(std::move(res_column), null_map_column); - else - return res_column; + return res_column; } }; diff --git a/src/Functions/seriesOutliersDetectTukey.cpp b/src/Functions/seriesOutliersDetectTukey.cpp index 4063d0ab85b..f0c683a0b28 100644 --- a/src/Functions/seriesOutliersDetectTukey.cpp +++ b/src/Functions/seriesOutliersDetectTukey.cpp @@ -105,12 +105,8 @@ public: { return col_res; } - else - throw Exception( - ErrorCodes::ILLEGAL_COLUMN, - "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), - getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", arguments[0].column->getName(), getName()); } private: diff --git a/src/Functions/splitByRegexp.cpp b/src/Functions/splitByRegexp.cpp index 042db97794d..eab996c98bf 100644 --- a/src/Functions/splitByRegexp.cpp +++ b/src/Functions/splitByRegexp.cpp @@ -170,9 +170,8 @@ public: { if (patternIsTrivialChar(arguments)) return FunctionFactory::instance().getImpl("splitByChar", context)->build(arguments); - else - return std::make_unique( - split_by_regexp, collections::map(arguments, [](const auto & elem) { return elem.type; }), return_type); + return std::make_unique( + split_by_regexp, collections::map(arguments, [](const auto & elem) { return elem.type; }), return_type); } DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override diff --git a/src/Functions/stl.hpp b/src/Functions/stl.hpp index 9d4fa30e2e3..48bc3793f55 100644 --- a/src/Functions/stl.hpp +++ b/src/Functions/stl.hpp @@ -55,38 +55,44 @@ inline bool est(const float* y, size_t n, size_t len, int ideg, float xs, float* if (a <= 0.0) { return false; - } else { // weighted least squares - for (auto j = nleft; j <= nright; j++) { // make sum of w(j) == 1 - w[j - 1] /= a; - } - - if (h > 0.0 && ideg > 0) { // use linear fit - auto a = 0.0; - for (auto j = nleft; j <= nright; j++) { // weighted center of x values - a += w[j - 1] * ((float) j); - } - auto b = xs - a; - auto c = 0.0; - for (auto j = nleft; j <= nright; j++) { - c += w[j - 1] * pow(((float) j) - a, 2); - } - if (sqrt(c) > 0.001 * range) { - b /= c; - - // points are spread out enough to compute slope - for (auto j = nleft; j <= nright; j++) { - w[j - 1] *= b * (((float) j) - a) + 1.0; - } - } - } - - *ys = 0.0; - for (auto j = nleft; j <= nright; j++) { - *ys += w[j - 1] * y[j - 1]; - } - - return true; + } // weighted least squares + for (auto j = nleft; j <= nright; j++) + { // make sum of w(j) == 1 + w[j - 1] /= a; } + + if (h > 0.0 && ideg > 0) + { // use linear fit + auto a = 0.0; + for (auto j = nleft; j <= nright; j++) + { // weighted center of x values + a += w[j - 1] * ((float)j); + } + auto b = xs - a; + auto c = 0.0; + for (auto j = nleft; j <= nright; j++) + { + c += w[j - 1] * pow(((float)j) - a, 2); + } + if (sqrt(c) > 0.001 * range) + { + b /= c; + + // points are spread out enough to compute slope + for (auto j = nleft; j <= nright; j++) + { + w[j - 1] *= b * (((float)j) - a) + 1.0; + } + } + } + + *ys = 0.0; + for (auto j = nleft; j <= nright; j++) + { + *ys += w[j - 1] * y[j - 1]; + } + + return true; } inline void ess(const float* y, size_t n, size_t len, int ideg, size_t njump, bool userw, const float* rw, float* ys, float* res) { diff --git a/src/Functions/stringCutToZero.cpp b/src/Functions/stringCutToZero.cpp index 16e57d741fa..ca0c713edf6 100644 --- a/src/Functions/stringCutToZero.cpp +++ b/src/Functions/stringCutToZero.cpp @@ -80,10 +80,8 @@ public: col_res = std::move(col_str); return true; } - else - { - return false; - } + + return false; } static bool tryExecuteFixedString(const IColumn * col, ColumnPtr & col_res, size_t input_rows_count) @@ -124,10 +122,8 @@ public: col_res = std::move(col_str); return true; } - else - { - return false; - } + + return false; } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override diff --git a/src/Functions/substring.cpp b/src/Functions/substring.cpp index 51980eb6b9c..caf1c672e53 100644 --- a/src/Functions/substring.cpp +++ b/src/Functions/substring.cpp @@ -153,8 +153,15 @@ public: bool all_ascii = isAllASCII(col->getChars().data(), col->getChars().size()); if (all_ascii) return executeForSource(column_offset, column_length, column_offset_const, column_length_const, offset, length, StringSource(*col), input_rows_count); - else - return executeForSource(column_offset, column_length, column_offset_const, column_length_const, offset, length, UTF8StringSource(*col), input_rows_count); + return executeForSource( + column_offset, + column_length, + column_offset_const, + column_length_const, + offset, + length, + UTF8StringSource(*col), + input_rows_count); } if (const ColumnConst * col_const = checkAndGetColumnConst(column_string.get())) @@ -163,8 +170,15 @@ public: bool all_ascii = isAllASCII(reinterpret_cast(str_ref.data), str_ref.size); if (all_ascii) return executeForSource(column_offset, column_length, column_offset_const, column_length_const, offset, length, ConstSource(*col_const), input_rows_count); - else - return executeForSource(column_offset, column_length, column_offset_const, column_length_const, offset, length, ConstSource(*col_const), input_rows_count); + return executeForSource( + column_offset, + column_length, + column_offset_const, + column_length_const, + offset, + length, + ConstSource(*col_const), + input_rows_count); } throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", arguments[0].column->getName(), getName()); } diff --git a/src/Functions/substringIndex.cpp b/src/Functions/substringIndex.cpp index dc12ae193ff..550ed729205 100644 --- a/src/Functions/substringIndex.cpp +++ b/src/Functions/substringIndex.cpp @@ -261,28 +261,26 @@ namespace } return {begin, static_cast(pos - begin - delim.size())}; } - else + + Int64 total = 0; + while (pos < end && end != (pos = searcher->search(pos, end - pos))) { - Int64 total = 0; - while (pos < end && end != (pos = searcher->search(pos, end - pos))) - { - pos += delim.size(); - ++total; - } - - if (total + count < 0) - return str_ref; - - pos = begin; - Int64 i = 0; - Int64 count_from_left = total + 1 + count; - while (i < count_from_left && pos < end && end != (pos = searcher->search(pos, end - pos))) - { - pos += delim.size(); - ++i; - } - return {pos, static_cast(end - pos)}; + pos += delim.size(); + ++total; } + + if (total + count < 0) + return str_ref; + + pos = begin; + Int64 i = 0; + Int64 count_from_left = total + 1 + count; + while (i < count_from_left && pos < end && end != (pos = searcher->search(pos, end - pos))) + { + pos += delim.size(); + ++i; + } + return {pos, static_cast(end - pos)}; } static StringRef substringIndex(const StringRef & str_ref, char delim, Int64 count) diff --git a/src/Functions/svg.cpp b/src/Functions/svg.cpp index 550fe29cfc4..da177d9f35d 100644 --- a/src/Functions/svg.cpp +++ b/src/Functions/svg.cpp @@ -54,7 +54,7 @@ public: { throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "Incorrect number of arguments: expected 1 or 2 arguments"); } - else if (arguments.size() == 2 && checkAndGetDataType(arguments[1].get()) == nullptr) + if (arguments.size() == 2 && checkAndGetDataType(arguments[1].get()) == nullptr) { throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Second argument should be String"); } diff --git a/src/Functions/throwIf.cpp b/src/Functions/throwIf.cpp index 73ad313aeed..f43306fa61a 100644 --- a/src/Functions/throwIf.cpp +++ b/src/Functions/throwIf.cpp @@ -145,10 +145,10 @@ private: throw Exception::createRuntime( error_code.value_or(ErrorCodes::FUNCTION_THROW_IF_VALUE_IS_NON_ZERO), *message); - else - throw Exception( - error_code.value_or(ErrorCodes::FUNCTION_THROW_IF_VALUE_IS_NON_ZERO), - "Value passed to '{}' function is non-zero", getName()); + throw Exception( + error_code.value_or(ErrorCodes::FUNCTION_THROW_IF_VALUE_IS_NON_ZERO), + "Value passed to '{}' function is non-zero", + getName()); } size_t result_size = in_untyped->size(); diff --git a/src/Functions/timeSlots.cpp b/src/Functions/timeSlots.cpp index b62bb20c64e..e72252fcf75 100644 --- a/src/Functions/timeSlots.cpp +++ b/src/Functions/timeSlots.cpp @@ -266,14 +266,11 @@ public: { return std::make_shared(std::make_shared(extractTimeZoneNameFromFunctionArguments(arguments, 3, 0, false))); } - else - { - auto start_time_scale = assert_cast(*arguments[0].type).getScale(); - auto duration_scale = assert_cast(*arguments[1].type).getScale(); - return std::make_shared( - std::make_shared(std::max(start_time_scale, duration_scale), extractTimeZoneNameFromFunctionArguments(arguments, 3, 0, false))); - } + auto start_time_scale = assert_cast(*arguments[0].type).getScale(); + auto duration_scale = assert_cast(*arguments[1].type).getScale(); + return std::make_shared(std::make_shared( + std::max(start_time_scale, duration_scale), extractTimeZoneNameFromFunctionArguments(arguments, 3, 0, false))); } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override @@ -305,14 +302,26 @@ public: TimeSlotsImpl::vectorVector(dt_starts->getData(), durations->getData(), time_slot_size, res_values, res->getOffsets(), input_rows_count); return res; } - else if (dt_starts && const_durations) + if (dt_starts && const_durations) { - TimeSlotsImpl::vectorConstant(dt_starts->getData(), const_durations->getValue(), time_slot_size, res_values, res->getOffsets(), input_rows_count); + TimeSlotsImpl::vectorConstant( + dt_starts->getData(), + const_durations->getValue(), + time_slot_size, + res_values, + res->getOffsets(), + input_rows_count); return res; } - else if (dt_const_starts && durations) + if (dt_const_starts && durations) { - TimeSlotsImpl::constantVector(dt_const_starts->getValue(), durations->getData(), time_slot_size, res_values, res->getOffsets(), input_rows_count); + TimeSlotsImpl::constantVector( + dt_const_starts->getValue(), + durations->getData(), + time_slot_size, + res_values, + res->getOffsets(), + input_rows_count); return res; } } @@ -350,18 +359,32 @@ public: start_time_scale, duration_scale, time_slot_scale, input_rows_count); return res; } - else if (starts && const_durations) + if (starts && const_durations) { TimeSlotsImpl::vectorConstant( - starts->getData(), const_durations->getValue(), time_slot_size, res_values, res->getOffsets(), - start_time_scale, duration_scale, time_slot_scale, input_rows_count); + starts->getData(), + const_durations->getValue(), + time_slot_size, + res_values, + res->getOffsets(), + start_time_scale, + duration_scale, + time_slot_scale, + input_rows_count); return res; } - else if (const_starts && durations) + if (const_starts && durations) { TimeSlotsImpl::constantVector( - const_starts->getValue(), durations->getData(), time_slot_size, res_values, res->getOffsets(), - start_time_scale, duration_scale, time_slot_scale, input_rows_count); + const_starts->getValue(), + durations->getData(), + time_slot_size, + res_values, + res->getOffsets(), + start_time_scale, + duration_scale, + time_slot_scale, + input_rows_count); return res; } } @@ -371,11 +394,13 @@ public: throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal columns {}, {}, {} of arguments of function {}", arguments[0].column->getName(), arguments[1].column->getName(), arguments[2].column->getName(), getName()); } - else - { - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal columns {}, {} of arguments of function {}", - arguments[0].column->getName(), arguments[1].column->getName(), getName()); - } + + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, + "Illegal columns {}, {} of arguments of function {}", + arguments[0].column->getName(), + arguments[1].column->getName(), + getName()); } }; diff --git a/src/Functions/timezoneOf.cpp b/src/Functions/timezoneOf.cpp index 7a5957a5dbc..7f873d19b84 100644 --- a/src/Functions/timezoneOf.cpp +++ b/src/Functions/timezoneOf.cpp @@ -39,8 +39,7 @@ public: if (isDateTime(type_no_nullable) || isDateTime64(type_no_nullable)) return std::make_shared(); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Bad argument for function {}, should be DateTime or DateTime64", name); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Bad argument for function {}, should be DateTime or DateTime64", name); } bool useDefaultImplementationForNulls() const override { return false; } diff --git a/src/Functions/toLowCardinality.cpp b/src/Functions/toLowCardinality.cpp index 9b050d47a90..e3c9fd71f51 100644 --- a/src/Functions/toLowCardinality.cpp +++ b/src/Functions/toLowCardinality.cpp @@ -39,12 +39,10 @@ public: if (arg.type->lowCardinality()) return arg.column; - else - { - auto column = res_type->createColumn(); - typeid_cast(*column).insertRangeFromFullColumn(*arg.column, 0, arg.column->size()); - return column; - } + + auto column = res_type->createColumn(); + typeid_cast(*column).insertRangeFromFullColumn(*arg.column, 0, arg.column->size()); + return column; } }; diff --git a/src/Functions/transform.cpp b/src/Functions/transform.cpp index 0dfc9197845..45f0a7f5c17 100644 --- a/src/Functions/transform.cpp +++ b/src/Functions/transform.cpp @@ -123,19 +123,17 @@ namespace checkAllowedType(ret); return ret; } - else - { - auto ret = tryGetLeastSupertype(DataTypes{type_arr_to_nested, arguments[3]}); - if (!ret) - throw Exception( - ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Function {} have signature: " - "transform(T, Array(T), Array(U), U) -> U; " - "or transform(T, Array(T), Array(T)) -> T; where T and U are types.", - getName()); - checkAllowedType(ret); - return ret; - } + + auto ret = tryGetLeastSupertype(DataTypes{type_arr_to_nested, arguments[3]}); + if (!ret) + throw Exception( + ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, + "Function {} have signature: " + "transform(T, Array(T), Array(U), U) -> U; " + "or transform(T, Array(T), Array(T)) -> T; where T and U are types.", + getName()); + checkAllowedType(ret); + return ret; } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr & result_type, size_t input_rows_count) const override @@ -171,7 +169,7 @@ namespace ? default_non_const : castColumn(arguments[0], result_type); } - else if (cache.table_num_to_idx) + if (cache.table_num_to_idx) { if (!executeNum>(in, *column_result, default_non_const, *in_casted, input_rows_count) && !executeNum>(in, *column_result, default_non_const, *in_casted, input_rows_count) @@ -186,7 +184,8 @@ namespace && !executeNum>(in, *column_result, default_non_const, *in_casted, input_rows_count) && !executeNum>(in, *column_result, default_non_const, *in_casted, input_rows_count)) { - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", in->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", in->getName(), getName()); } } else if (cache.table_string_to_idx) diff --git a/src/Functions/translate.cpp b/src/Functions/translate.cpp index 366640d7d20..f7077f99629 100644 --- a/src/Functions/translate.cpp +++ b/src/Functions/translate.cpp @@ -305,12 +305,10 @@ public: if (isString(arguments[0])) return std::make_shared(); - else - { - const auto * ptr = checkAndGetDataType(arguments[0].get()); - chassert(ptr); - return std::make_shared(ptr->getN()); - } + + const auto * ptr = checkAndGetDataType(arguments[0].get()); + chassert(ptr); + return std::make_shared(ptr->getN()); } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override @@ -335,15 +333,14 @@ public: Impl::vector(col->getChars(), col->getOffsets(), map_from, map_to, col_res->getChars(), col_res->getOffsets(), input_rows_count); return col_res; } - else if (const ColumnFixedString * col_fixed = checkAndGetColumn(column_src.get())) + if (const ColumnFixedString * col_fixed = checkAndGetColumn(column_src.get())) { auto col_res = ColumnFixedString::create(col_fixed->getN()); Impl::vectorFixed(col_fixed->getChars(), col_fixed->getN(), map_from, map_to, col_res->getChars()); return col_res; } - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", - arguments[0].column->getName(), getName()); + throw Exception( + ErrorCodes::ILLEGAL_COLUMN, "Illegal column {} of first argument of function {}", arguments[0].column->getName(), getName()); } }; diff --git a/src/Functions/tuple.h b/src/Functions/tuple.h index 03ba7ec9ef2..4ce90579245 100644 --- a/src/Functions/tuple.h +++ b/src/Functions/tuple.h @@ -60,8 +60,7 @@ public: if (enable_named_columns && name_set.size() == names.size() && std::all_of(names.cbegin(), names.cend(), [](const auto & n) { return isUnquotedIdentifier(n); })) return std::make_shared(types, names); - else - return std::make_shared(types); + return std::make_shared(types); } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override diff --git a/src/Functions/tupleElement.cpp b/src/Functions/tupleElement.cpp index 96b5a047419..49d8fa759e8 100644 --- a/src/Functions/tupleElement.cpp +++ b/src/Functions/tupleElement.cpp @@ -75,8 +75,7 @@ public: return return_type; } - else - return arguments[2].type; + return arguments[2].type; } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override @@ -136,31 +135,24 @@ private: if (index > 0 && index <= tuple.getElements().size()) return {index - 1}; - else - { - if (argument_size == 2) - throw Exception(ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK, "Tuple doesn't have element with index '{}'", index); - return std::nullopt; - } + if (argument_size == 2) + throw Exception(ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK, "Tuple doesn't have element with index '{}'", index); + return std::nullopt; } - else if (const auto * name_col = checkAndGetColumnConst(index_column.get())) + if (const auto * name_col = checkAndGetColumnConst(index_column.get())) { std::optional index = tuple.tryGetPositionByName(name_col->getValue()); if (index.has_value()) return index; - else - { - if (argument_size == 2) - throw Exception(ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK, "Tuple doesn't have element with name '{}'", name_col->getValue()); - return std::nullopt; - } + + if (argument_size == 2) + throw Exception( + ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK, "Tuple doesn't have element with name '{}'", name_col->getValue()); + return std::nullopt; } - else - throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, - "Second argument to {} must be a constant UInt or String", - getName()); + throw Exception(ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT, "Second argument to {} must be a constant UInt or String", getName()); } }; diff --git a/src/Functions/variantElement.cpp b/src/Functions/variantElement.cpp index 80d34083d9d..f5c07a76d67 100644 --- a/src/Functions/variantElement.cpp +++ b/src/Functions/variantElement.cpp @@ -79,8 +79,7 @@ public: return return_type; } - else - return arguments[2].type; + return arguments[2].type; } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t input_rows_count) const override diff --git a/src/Functions/widthBucket.cpp b/src/Functions/widthBucket.cpp index ba24362034f..55b6b27df1e 100644 --- a/src/Functions/widthBucket.cpp +++ b/src/Functions/widthBucket.cpp @@ -99,7 +99,7 @@ class FunctionWidthBucket : public IFunction { return 0; } - else if (operand >= high) + if (operand >= high) { return count + 1; } diff --git a/src/IO/Archives/LibArchiveWriter.cpp b/src/IO/Archives/LibArchiveWriter.cpp index 55bc4c1f88c..4bbbc90a4a3 100644 --- a/src/IO/Archives/LibArchiveWriter.cpp +++ b/src/IO/Archives/LibArchiveWriter.cpp @@ -114,8 +114,7 @@ private: { if (size) return size; - else - return offset(); + return offset(); } void closeFile(bool throw_if_error) diff --git a/src/IO/Archives/ZipArchiveWriter.cpp b/src/IO/Archives/ZipArchiveWriter.cpp index 0cfe921f33f..149b05dc201 100644 --- a/src/IO/Archives/ZipArchiveWriter.cpp +++ b/src/IO/Archives/ZipArchiveWriter.cpp @@ -345,20 +345,19 @@ int ZipArchiveWriter::compressionMethodToInt(const String & compression_method_) { if (compression_method_.empty()) return MZ_COMPRESS_METHOD_DEFLATE; /// By default the compression method is "deflate". - else if (compression_method_ == kStore) + if (compression_method_ == kStore) return MZ_COMPRESS_METHOD_STORE; - else if (compression_method_ == kDeflate) + if (compression_method_ == kDeflate) return MZ_COMPRESS_METHOD_DEFLATE; - else if (compression_method_ == kBzip2) + if (compression_method_ == kBzip2) return MZ_COMPRESS_METHOD_BZIP2; - else if (compression_method_ == kLzma) + if (compression_method_ == kLzma) return MZ_COMPRESS_METHOD_LZMA; - else if (compression_method_ == kZstd) + if (compression_method_ == kZstd) return MZ_COMPRESS_METHOD_ZSTD; - else if (compression_method_ == kXz) + if (compression_method_ == kXz) return MZ_COMPRESS_METHOD_XZ; - else - throw Exception(ErrorCodes::CANNOT_PACK_ARCHIVE, "Unknown compression method specified for a zip archive: {}", compression_method_); + throw Exception(ErrorCodes::CANNOT_PACK_ARCHIVE, "Unknown compression method specified for a zip archive: {}", compression_method_); } String ZipArchiveWriter::intToCompressionMethod(int compression_method_) diff --git a/src/IO/AsynchronousReadBufferFromFileDescriptor.cpp b/src/IO/AsynchronousReadBufferFromFileDescriptor.cpp index 6c4bd09b76f..06f9f98c955 100644 --- a/src/IO/AsynchronousReadBufferFromFileDescriptor.cpp +++ b/src/IO/AsynchronousReadBufferFromFileDescriptor.cpp @@ -196,7 +196,7 @@ off_t AsynchronousReadBufferFromFileDescriptor::seek(off_t offset, int whence) return new_pos; } - else if (prefetch_future.valid()) + if (prefetch_future.valid()) { /// Read from prefetch buffer and recheck if the new position is valid inside. if (nextImpl()) diff --git a/src/IO/AzureBlobStorage/copyAzureBlobStorageFile.cpp b/src/IO/AzureBlobStorage/copyAzureBlobStorageFile.cpp index 72b8110fb75..93bff3b3dc2 100644 --- a/src/IO/AzureBlobStorage/copyAzureBlobStorageFile.cpp +++ b/src/IO/AzureBlobStorage/copyAzureBlobStorageFile.cpp @@ -106,9 +106,9 @@ namespace if (!max_part_number) throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "max_blocks_in_multipart_upload must not be 0"); - else if (!min_upload_part_size) + if (!min_upload_part_size) throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "min_upload_part_size must not be 0"); - else if (max_upload_part_size < min_upload_part_size) + if (max_upload_part_size < min_upload_part_size) throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "max_upload_part_size must not be less than min_upload_part_size"); size_t part_size = min_upload_part_size; @@ -383,8 +383,12 @@ void copyAzureBlobStorageFile( if (copy_status.HasValue()) throw Exception(ErrorCodes::AZURE_BLOB_STORAGE_ERROR, "Copy from {} to {} failed with status {} description {} (operation is done {})", src_blob, dest_blob, copy_status.Value().ToString(), copy_status_description.Value(), operation.IsDone()); - else - throw Exception(ErrorCodes::AZURE_BLOB_STORAGE_ERROR, "Copy from {} to {} didn't complete with success status (operation is done {})", src_blob, dest_blob, operation.IsDone()); + throw Exception( + ErrorCodes::AZURE_BLOB_STORAGE_ERROR, + "Copy from {} to {} didn't complete with success status (operation is done {})", + src_blob, + dest_blob, + operation.IsDone()); } } } diff --git a/src/IO/BrotliReadBuffer.cpp b/src/IO/BrotliReadBuffer.cpp index 1863cef8a39..f02919daa97 100644 --- a/src/IO/BrotliReadBuffer.cpp +++ b/src/IO/BrotliReadBuffer.cpp @@ -85,13 +85,8 @@ bool BrotliReadBuffer::nextImpl() eof_flag = true; return !working_buffer.empty(); } - else - { - throw Exception( - ErrorCodes::BROTLI_READ_FAILED, - "brotli decode error{}", - getExceptionEntryWithFileName(*in)); - } + + throw Exception(ErrorCodes::BROTLI_READ_FAILED, "brotli decode error{}", getExceptionEntryWithFileName(*in)); } if (brotli->result == BROTLI_DECODER_RESULT_ERROR) diff --git a/src/IO/CompressionMethod.cpp b/src/IO/CompressionMethod.cpp index 22913125e99..82a7a0d6340 100644 --- a/src/IO/CompressionMethod.cpp +++ b/src/IO/CompressionMethod.cpp @@ -60,22 +60,21 @@ CompressionMethod chooseHTTPCompressionMethod(const std::string & list) if (std::string::npos != list.find("zstd")) return CompressionMethod::Zstd; - else if (std::string::npos != list.find("br")) + if (std::string::npos != list.find("br")) return CompressionMethod::Brotli; - else if (std::string::npos != list.find("lz4")) + if (std::string::npos != list.find("lz4")) return CompressionMethod::Lz4; - else if (std::string::npos != list.find("snappy")) + if (std::string::npos != list.find("snappy")) return CompressionMethod::Snappy; - else if (std::string::npos != list.find("gzip")) + if (std::string::npos != list.find("gzip")) return CompressionMethod::Gzip; - else if (std::string::npos != list.find("deflate")) + if (std::string::npos != list.find("deflate")) return CompressionMethod::Zlib; - else if (std::string::npos != list.find("xz")) + if (std::string::npos != list.find("xz")) return CompressionMethod::Xz; - else if (std::string::npos != list.find("bz2")) + if (std::string::npos != list.find("bz2")) return CompressionMethod::Bzip2; - else - return CompressionMethod::None; + return CompressionMethod::None; } CompressionMethod chooseCompressionMethod(const std::string & path, const std::string & hint) diff --git a/src/IO/ConnectionTimeouts.cpp b/src/IO/ConnectionTimeouts.cpp index ea160c135d8..98cd28efca2 100644 --- a/src/IO/ConnectionTimeouts.cpp +++ b/src/IO/ConnectionTimeouts.cpp @@ -27,8 +27,7 @@ Poco::Timespan ConnectionTimeouts::saturate(Poco::Timespan timespan, Poco::Times { if (limit.totalMicroseconds() == 0) return timespan; - else - return (timespan > limit) ? limit : timespan; + return (timespan > limit) ? limit : timespan; } /// Timeouts for the case when we have just single attempt to connect. diff --git a/src/IO/FileEncryptionCommon.cpp b/src/IO/FileEncryptionCommon.cpp index 6e294045ae7..61f76a25847 100644 --- a/src/IO/FileEncryptionCommon.cpp +++ b/src/IO/FileEncryptionCommon.cpp @@ -226,15 +226,14 @@ Algorithm parseAlgorithmFromString(const String & str) { if (boost::iequals(str, "aes_128_ctr")) return Algorithm::AES_128_CTR; - else if (boost::iequals(str, "aes_192_ctr")) + if (boost::iequals(str, "aes_192_ctr")) return Algorithm::AES_192_CTR; - else if (boost::iequals(str, "aes_256_ctr")) + if (boost::iequals(str, "aes_256_ctr")) return Algorithm::AES_256_CTR; - else - throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "Encryption algorithm '{}' is not supported, specify one of the following: aes_128_ctr, aes_192_ctr, aes_256_ctr", - str); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Encryption algorithm '{}' is not supported, specify one of the following: aes_128_ctr, aes_192_ctr, aes_256_ctr", + str); } void checkKeySize(size_t key_size, Algorithm algorithm) { checkKeySize(getCipher(algorithm), key_size); } diff --git a/src/IO/HadoopSnappyReadBuffer.cpp b/src/IO/HadoopSnappyReadBuffer.cpp index 28588854268..8107d11dc17 100644 --- a/src/IO/HadoopSnappyReadBuffer.cpp +++ b/src/IO/HadoopSnappyReadBuffer.cpp @@ -224,7 +224,7 @@ bool HadoopSnappyReadBuffer::nextImpl() } return true; } - else if (decoder->result != Status::NEEDS_MORE_INPUT) + if (decoder->result != Status::NEEDS_MORE_INPUT) { throw Exception( ErrorCodes::SNAPPY_UNCOMPRESS_FAILED, diff --git a/src/IO/HashingWriteBuffer.h b/src/IO/HashingWriteBuffer.h index 8edfa45a6be..c18d5c4a5ef 100644 --- a/src/IO/HashingWriteBuffer.h +++ b/src/IO/HashingWriteBuffer.h @@ -26,8 +26,7 @@ public: { if (block_pos) return CityHash_v1_0_2::CityHash128WithSeed(BufferWithOwnMemory::memory.data(), block_pos, state); - else - return state; + return state; } void append(DB::BufferBase::Position data) diff --git a/src/IO/LZMAInflatingReadBuffer.cpp b/src/IO/LZMAInflatingReadBuffer.cpp index a6f3c74ae73..ceb25fddea1 100644 --- a/src/IO/LZMAInflatingReadBuffer.cpp +++ b/src/IO/LZMAInflatingReadBuffer.cpp @@ -75,15 +75,13 @@ bool LZMAInflatingReadBuffer::nextImpl() eof_flag = true; return !working_buffer.empty(); } - else - { - throw Exception( - ErrorCodes::LZMA_STREAM_DECODER_FAILED, - "lzma decoder finished, but input stream has not exceeded: error code: {}; lzma version: {}{}", - ret, - LZMA_VERSION_STRING, - getExceptionEntryWithFileName(*in)); - } + + throw Exception( + ErrorCodes::LZMA_STREAM_DECODER_FAILED, + "lzma decoder finished, but input stream has not exceeded: error code: {}; lzma version: {}{}", + ret, + LZMA_VERSION_STRING, + getExceptionEntryWithFileName(*in)); } if (ret != LZMA_OK) diff --git a/src/IO/ReadBufferFromFileDescriptor.cpp b/src/IO/ReadBufferFromFileDescriptor.cpp index 51a1a5d8d93..2370a385b09 100644 --- a/src/IO/ReadBufferFromFileDescriptor.cpp +++ b/src/IO/ReadBufferFromFileDescriptor.cpp @@ -173,6 +173,7 @@ off_t ReadBufferFromFileDescriptor::seek(off_t offset, int whence) if (new_pos + (working_buffer.end() - pos) == file_offset_of_buffer_end) return new_pos; + /// NOLINTBEGIN(readability-else-after-return) if (file_offset_of_buffer_end - working_buffer.size() <= new_pos && new_pos <= file_offset_of_buffer_end) { @@ -232,6 +233,7 @@ off_t ReadBufferFromFileDescriptor::seek(off_t offset, int whence) return seek_pos; } + /// NOLINTEND(readability-else-after-return) } diff --git a/src/IO/ReadBufferFromMemory.cpp b/src/IO/ReadBufferFromMemory.cpp index ede2c531e43..6895cdb8b0a 100644 --- a/src/IO/ReadBufferFromMemory.cpp +++ b/src/IO/ReadBufferFromMemory.cpp @@ -18,11 +18,13 @@ off_t ReadBufferFromMemory::seek(off_t offset, int whence) working_buffer = internal_buffer; /// We need to restore `working_buffer` in case the position was at EOF before this seek(). return static_cast(pos - internal_buffer.begin()); } - else - throw Exception(ErrorCodes::SEEK_POSITION_OUT_OF_BOUND, "Seek position is out of bounds. Offset: {}, Max: {}", - offset, std::to_string(static_cast(internal_buffer.end() - internal_buffer.begin()))); + throw Exception( + ErrorCodes::SEEK_POSITION_OUT_OF_BOUND, + "Seek position is out of bounds. Offset: {}, Max: {}", + offset, + std::to_string(static_cast(internal_buffer.end() - internal_buffer.begin()))); } - else if (whence == SEEK_CUR) + if (whence == SEEK_CUR) { Position new_pos = pos + offset; if (new_pos >= internal_buffer.begin() && new_pos <= internal_buffer.end()) @@ -31,12 +33,13 @@ off_t ReadBufferFromMemory::seek(off_t offset, int whence) working_buffer = internal_buffer; /// We need to restore `working_buffer` in case the position was at EOF before this seek(). return static_cast(pos - internal_buffer.begin()); } - else - throw Exception(ErrorCodes::SEEK_POSITION_OUT_OF_BOUND, "Seek position is out of bounds. Offset: {}, Max: {}", - offset, std::to_string(static_cast(internal_buffer.end() - internal_buffer.begin()))); + throw Exception( + ErrorCodes::SEEK_POSITION_OUT_OF_BOUND, + "Seek position is out of bounds. Offset: {}, Max: {}", + offset, + std::to_string(static_cast(internal_buffer.end() - internal_buffer.begin()))); } - else - throw Exception(ErrorCodes::CANNOT_SEEK_THROUGH_FILE, "Only SEEK_SET and SEEK_CUR seek modes allowed."); + throw Exception(ErrorCodes::CANNOT_SEEK_THROUGH_FILE, "Only SEEK_SET and SEEK_CUR seek modes allowed."); } off_t ReadBufferFromMemory::getPosition() diff --git a/src/IO/ReadBufferFromPocoSocketChunked.cpp b/src/IO/ReadBufferFromPocoSocketChunked.cpp index 4a1e3732a55..9c957646e3c 100644 --- a/src/IO/ReadBufferFromPocoSocketChunked.cpp +++ b/src/IO/ReadBufferFromPocoSocketChunked.cpp @@ -113,8 +113,7 @@ bool ReadBufferFromPocoSocketChunked::nextImpl() else c_pos = pos + sizeof(next_chunk); // bypass chunk end marker - if (c_pos > data_end) - c_pos = data_end; + c_pos = std::min(c_pos, data_end); if (!loadNextChunk(c_pos)) return false; diff --git a/src/IO/ReadBufferFromS3.cpp b/src/IO/ReadBufferFromS3.cpp index a6176723497..e421753e823 100644 --- a/src/IO/ReadBufferFromS3.cpp +++ b/src/IO/ReadBufferFromS3.cpp @@ -427,11 +427,9 @@ Aws::S3::Model::GetObjectResult ReadBufferFromS3::sendRequest(size_t attempt, si if (outcome.IsSuccess()) return outcome.GetResultWithOwnership(); - else - { - const auto & error = outcome.GetError(); - throw S3Exception(error.GetMessage(), error.GetErrorType()); - } + + const auto & error = outcome.GetError(); + throw S3Exception(error.GetMessage(), error.GetErrorType()); } } diff --git a/src/IO/ReadHelpers.cpp b/src/IO/ReadHelpers.cpp index a38dc1ecefb..caaab68ba1a 100644 --- a/src/IO/ReadHelpers.cpp +++ b/src/IO/ReadHelpers.cpp @@ -1372,8 +1372,7 @@ ReturnType readDateTextFallback(LocalDate & date, ReadBuffer & buf, const char * ++buf.position(); return true; } - else - return false; + return false; }; UInt16 year = 0; @@ -1606,7 +1605,7 @@ ReturnType skipJSONFieldImpl(ReadBuffer & buf, StringRef name_of_field, const Fo throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected EOF for key '{}'", name_of_field.toString()); return ReturnType(false); } - else if (*buf.position() == '"') /// skip double-quoted string + if (*buf.position() == '"') /// skip double-quoted string { NullOutput sink; if constexpr (throw_exception) @@ -2112,13 +2111,13 @@ ReturnType readQuotedFieldInto(Vector & s, ReadBuffer & buf) if (*buf.position() == '\'') return readQuotedStringFieldInto(s, buf); - else if (*buf.position() == '[') + if (*buf.position() == '[') return readQuotedFieldInBracketsInto(s, buf); - else if (*buf.position() == '(') + if (*buf.position() == '(') return readQuotedFieldInBracketsInto(s, buf); - else if (*buf.position() == '{') + if (*buf.position() == '{') return readQuotedFieldInBracketsInto(s, buf); - else if (checkCharCaseInsensitive('n', buf)) + if (checkCharCaseInsensitive('n', buf)) { /// NULL or NaN if (checkCharCaseInsensitive('u', buf)) diff --git a/src/IO/ReadHelpers.h b/src/IO/ReadHelpers.h index 05198361ca2..50131781e77 100644 --- a/src/IO/ReadHelpers.h +++ b/src/IO/ReadHelpers.h @@ -314,8 +314,7 @@ inline ReturnType readBoolTextWord(bool & x, ReadBuffer & buf, bool support_uppe x = true; break; } - else - [[fallthrough]]; + [[fallthrough]]; } case 'F': { @@ -328,8 +327,7 @@ inline ReturnType readBoolTextWord(bool & x, ReadBuffer & buf, bool support_uppe x = false; break; } - else - [[fallthrough]]; + [[fallthrough]]; } default: { @@ -822,8 +820,7 @@ inline ReturnType readDateTextImpl(LocalDate & date, ReadBuffer & buf, const cha date = LocalDate(year, month, day); return ReturnType(true); } - else - return readDateTextFallback(date, buf, allowed_delimiters); + return readDateTextFallback(date, buf, allowed_delimiters); } inline void convertToDayNum(DayNum & date, ExtendedDayNum & from) @@ -935,18 +932,16 @@ inline ReturnType readUUIDTextImpl(UUID & uuid, ReadBuffer & buf) uuid = parseUUID({reinterpret_cast(s), size}); return ReturnType(true); } + + s[size] = 0; + + if constexpr (throw_exception) + { + throw Exception(ErrorCodes::CANNOT_PARSE_UUID, "Cannot parse uuid {}", s); + } else { - s[size] = 0; - - if constexpr (throw_exception) - { - throw Exception(ErrorCodes::CANNOT_PARSE_UUID, "Cannot parse uuid {}", s); - } - else - { - return ReturnType(false); - } + return ReturnType(false); } } @@ -1098,12 +1093,10 @@ inline ReturnType readDateTimeTextImpl(time_t & datetime, ReadBuffer & buf, cons return ReturnType(true); } - else - /// Why not readIntTextUnsafe? Because for needs of AdFox, parsing of unix timestamp with leading zeros is supported: 000...NNNN. - return readIntTextImpl(datetime, buf); + /// Why not readIntTextUnsafe? Because for needs of AdFox, parsing of unix timestamp with leading zeros is supported: 000...NNNN. + return readIntTextImpl(datetime, buf); } - else - return readDateTimeTextFallback(datetime, buf, date_lut, allowed_date_delimiters, allowed_time_delimiters); + return readDateTimeTextFallback(datetime, buf, date_lut, allowed_date_delimiters, allowed_time_delimiters); } template diff --git a/src/IO/ReadWriteBufferFromHTTP.cpp b/src/IO/ReadWriteBufferFromHTTP.cpp index 826862bb5b3..eb2d5128454 100644 --- a/src/IO/ReadWriteBufferFromHTTP.cpp +++ b/src/IO/ReadWriteBufferFromHTTP.cpp @@ -426,15 +426,15 @@ std::unique_ptr ReadWriteBufferFromHTTP::initialize() reason, ""); } - else - throw Exception( - ErrorCodes::HTTP_RANGE_NOT_SATISFIABLE, - "Cannot read with range: [{}, {}] (response status: {}, reason: {})", - *read_range.begin, - read_range.end ? toString(*read_range.end) : "-", - toString(response.getStatus()), response.getReason()); + throw Exception( + ErrorCodes::HTTP_RANGE_NOT_SATISFIABLE, + "Cannot read with range: [{}, {}] (response status: {}, reason: {})", + *read_range.begin, + read_range.end ? toString(*read_range.end) : "-", + toString(response.getStatus()), + response.getReason()); } - else if (read_range.end) + if (read_range.end) { /// We could have range.begin == 0 and range.end != 0 in case of DiskWeb and failing to read with partial content /// will affect only performance, so a warning is enough. diff --git a/src/IO/S3/AWSLogger.cpp b/src/IO/S3/AWSLogger.cpp index dcdba7753b2..a59ad83faf1 100644 --- a/src/IO/S3/AWSLogger.cpp +++ b/src/IO/S3/AWSLogger.cpp @@ -50,8 +50,7 @@ Aws::Utils::Logging::LogLevel AWSLogger::GetLogLevel() const { if (enable_s3_requests_logging) return Aws::Utils::Logging::LogLevel::Trace; - else - return Aws::Utils::Logging::LogLevel::Info; + return Aws::Utils::Logging::LogLevel::Info; } void AWSLogger::Log(Aws::Utils::Logging::LogLevel log_level, const char * tag, const char * format_str, ...) // NOLINT diff --git a/src/IO/S3/Credentials.cpp b/src/IO/S3/Credentials.cpp index fab3a0111eb..a3f671e76d9 100644 --- a/src/IO/S3/Credentials.cpp +++ b/src/IO/S3/Credentials.cpp @@ -151,10 +151,13 @@ Aws::String AWSEC2MetadataClient::getDefaultCredentialsSecurely() const /// At least the host should be available and reply, otherwise neither IMDSv2 nor IMDSv1 are usable. return {}; } - else if (response_code != Aws::Http::HttpResponseCode::OK || new_token.empty()) + if (response_code != Aws::Http::HttpResponseCode::OK || new_token.empty()) { - LOG_TRACE(logger, "Calling EC2MetadataService to get token failed, " - "falling back to a less secure way. HTTP response code: {}", response_code); + LOG_TRACE( + logger, + "Calling EC2MetadataService to get token failed, " + "falling back to a less secure way. HTTP response code: {}", + response_code); return getDefaultCredentials(); } @@ -444,20 +447,18 @@ AwsAuthSTSAssumeRoleWebIdentityCredentialsProvider::AwsAuthSTSAssumeRoleWebIdent LOG_WARNING(logger, "Token file must be specified to use STS AssumeRole web identity creds provider."); return; // No need to do further constructing } - else - { - LOG_DEBUG(logger, "Resolved token_file from profile_config or environment variable to be {}", token_file); - } + + LOG_DEBUG(logger, "Resolved token_file from profile_config or environment variable to be {}", token_file); + if (role_arn.empty()) { LOG_WARNING(logger, "RoleArn must be specified to use STS AssumeRole web identity creds provider."); return; // No need to do further constructing } - else - { - LOG_DEBUG(logger, "Resolved role_arn from profile_config or environment variable to be {}", role_arn); - } + + LOG_DEBUG(logger, "Resolved role_arn from profile_config or environment variable to be {}", role_arn); + if (tmp_region.empty()) { @@ -663,11 +664,9 @@ Aws::String SSOCredentialsProvider::loadAccessTokenFile(const Aws::String & sso_ expires_at = expiration; return tmp_access_token; } - else - { - LOG_TEST(logger, "Unable to open token file on path: {}", sso_access_token_path); - return ""; - } + + LOG_TEST(logger, "Unable to open token file on path: {}", sso_access_token_path); + return ""; } S3CredentialsProviderChain::S3CredentialsProviderChain( diff --git a/src/IO/S3/PocoHTTPClientFactory.cpp b/src/IO/S3/PocoHTTPClientFactory.cpp index abec907778c..f4db72abb8e 100644 --- a/src/IO/S3/PocoHTTPClientFactory.cpp +++ b/src/IO/S3/PocoHTTPClientFactory.cpp @@ -17,8 +17,8 @@ PocoHTTPClientFactory::CreateHttpClient(const Aws::Client::ClientConfiguration & { if (client_configuration.userAgent.starts_with("ClickHouse")) return std::make_shared(static_cast(client_configuration)); - else /// This client is created inside the AWS SDK with default settings to obtain ECS credentials from localhost. - return std::make_shared(client_configuration); + /// This client is created inside the AWS SDK with default settings to obtain ECS credentials from localhost. + return std::make_shared(client_configuration); } std::shared_ptr PocoHTTPClientFactory::CreateHttpRequest( diff --git a/src/IO/S3/copyS3File.cpp b/src/IO/S3/copyS3File.cpp index 361b5a707fd..941ecc818df 100644 --- a/src/IO/S3/copyS3File.cpp +++ b/src/IO/S3/copyS3File.cpp @@ -296,9 +296,9 @@ namespace if (!max_part_number) throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "max_part_number must not be 0"); - else if (!min_upload_part_size) + if (!min_upload_part_size) throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "min_upload_part_size must not be 0"); - else if (max_upload_part_size < min_upload_part_size) + if (max_upload_part_size < min_upload_part_size) throw Exception(ErrorCodes::INVALID_CONFIG_PARAMETER, "max_upload_part_size must not be less than min_upload_part_size"); size_t part_size = min_upload_part_size; @@ -769,21 +769,19 @@ namespace fallback_method(); break; } - else - { - // Can't come here with MinIO, MinIO allows single part upload for large objects. - LOG_INFO( - log, - "Single operation copy failed with error {} for Bucket: {}, Key: {}, Object size: {}, will retry with multipart " - "upload copy", - outcome.GetError().GetExceptionName(), - dest_bucket, - dest_key, - size); - performMultipartUploadCopy(); - break; - } + // Can't come here with MinIO, MinIO allows single part upload for large objects. + LOG_INFO( + log, + "Single operation copy failed with error {} for Bucket: {}, Key: {}, Object size: {}, will retry with multipart " + "upload copy", + outcome.GetError().GetExceptionName(), + dest_bucket, + dest_key, + size); + + performMultipartUploadCopy(); + break; } if ((outcome.GetError().GetErrorType() == Aws::S3::S3Errors::NO_SUCH_KEY) && (retries < max_retries)) diff --git a/src/IO/S3/getObjectInfo.cpp b/src/IO/S3/getObjectInfo.cpp index a21fb9fce54..37f7410f0f4 100644 --- a/src/IO/S3/getObjectInfo.cpp +++ b/src/IO/S3/getObjectInfo.cpp @@ -82,11 +82,13 @@ ObjectInfo getObjectInfo( { return *object_info; } - else if (throw_on_error) + if (throw_on_error) { - throw S3Exception(error.GetErrorType(), + throw S3Exception( + error.GetErrorType(), "Failed to get object info: {}. HTTP response code: {}", - error.GetMessage(), static_cast(error.GetResponseCode())); + error.GetMessage(), + static_cast(error.GetResponseCode())); } return {}; } diff --git a/src/IO/StdStreamBufFromReadBuffer.cpp b/src/IO/StdStreamBufFromReadBuffer.cpp index a814dff040b..ed3a682fbf0 100644 --- a/src/IO/StdStreamBufFromReadBuffer.cpp +++ b/src/IO/StdStreamBufFromReadBuffer.cpp @@ -54,12 +54,11 @@ std::streampos StdStreamBufFromReadBuffer::seekoff(std::streamoff off, std::ios_ { if (dir == std::ios_base::beg) return seekpos(off, which); - else if (dir == std::ios_base::cur) + if (dir == std::ios_base::cur) return seekpos(getCurrentPosition() + off, which); - else if (dir == std::ios_base::end) + if (dir == std::ios_base::end) return seekpos(size + off, which); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Wrong seek's base {}", static_cast(dir)); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Wrong seek's base {}", static_cast(dir)); } std::streampos StdStreamBufFromReadBuffer::seekpos(std::streampos pos, std::ios_base::openmode which) @@ -94,8 +93,7 @@ std::streampos StdStreamBufFromReadBuffer::getCurrentPosition() const { if (seekable_read_buffer) return seekable_read_buffer->getPosition(); - else - return read_buffer->count(); + return read_buffer->count(); } std::streamsize StdStreamBufFromReadBuffer::xsputn(const char*, std::streamsize) diff --git a/src/IO/WithFileName.cpp b/src/IO/WithFileName.cpp index 7b50b205935..8a3912749f0 100644 --- a/src/IO/WithFileName.cpp +++ b/src/IO/WithFileName.cpp @@ -18,12 +18,11 @@ String getFileNameFromReadBuffer(const ReadBuffer & in) { if (const auto * wrapper = dynamic_cast(&in)) return getFileNameFromReadBuffer(wrapper->getWrappedReadBuffer()); - else if (const auto * parallel = dynamic_cast(&in)) + if (const auto * parallel = dynamic_cast(&in)) return getFileNameFromReadBuffer(parallel->getReadBuffer()); - else if (const auto * peekable = dynamic_cast(&in)) + if (const auto * peekable = dynamic_cast(&in)) return getFileNameFromReadBuffer(peekable->getSubBuffer()); - else - return getFileName(in); + return getFileName(in); } String getExceptionEntryWithFileName(const ReadBuffer & in) diff --git a/src/IO/WithFileSize.cpp b/src/IO/WithFileSize.cpp index 54747cef8af..f111754470e 100644 --- a/src/IO/WithFileSize.cpp +++ b/src/IO/WithFileSize.cpp @@ -44,7 +44,7 @@ std::optional tryGetFileSizeFromReadBuffer(ReadBuffer & in) { if (auto * delegate = dynamic_cast(&in)) return tryGetFileSize(delegate->getWrappedReadBuffer()); - else if (auto * compressed = dynamic_cast(&in)) + if (auto * compressed = dynamic_cast(&in)) return tryGetFileSize(compressed->getWrappedReadBuffer()); return tryGetFileSize(in); } @@ -63,7 +63,7 @@ bool isBufferWithFileSize(const ReadBuffer & in) { return delegate->isWithFileSize(); } - else if (const auto * compressed = dynamic_cast(&in)) + if (const auto * compressed = dynamic_cast(&in)) { return isBufferWithFileSize(compressed->getWrappedReadBuffer()); } @@ -77,11 +77,11 @@ size_t getDataOffsetMaybeCompressed(const ReadBuffer & in) { return getDataOffsetMaybeCompressed(delegate->getWrappedReadBuffer()); } - else if (const auto * compressed = dynamic_cast(&in)) + if (const auto * compressed = dynamic_cast(&in)) { return getDataOffsetMaybeCompressed(compressed->getWrappedReadBuffer()); } - else if (const auto * peekable = dynamic_cast(&in)) + if (const auto * peekable = dynamic_cast(&in)) { return getDataOffsetMaybeCompressed(peekable->getSubBuffer()); } diff --git a/src/IO/WriteBufferFromArena.h b/src/IO/WriteBufferFromArena.h index f901f5bff77..0971431e0e4 100644 --- a/src/IO/WriteBufferFromArena.h +++ b/src/IO/WriteBufferFromArena.h @@ -4,6 +4,8 @@ #include #include +#include + namespace DB { @@ -51,8 +53,7 @@ private: /// the most stupid way possible, because the real fix for this is to /// tear down the entire WriteBuffer thing and implement it again, /// properly. - size_t continuation_size = std::max(size_t(1), - std::max(count(), arena.remainingSpaceInCurrentMemoryChunk())); + size_t continuation_size = std::max({size_t(1), count(), arena.remainingSpaceInCurrentMemoryChunk()}); /// allocContinue method will possibly move memory region to new place and modify "begin" pointer. diff --git a/src/IO/WriteHelpers.h b/src/IO/WriteHelpers.h index 6b0de441e94..a890248b3f4 100644 --- a/src/IO/WriteHelpers.h +++ b/src/IO/WriteHelpers.h @@ -318,6 +318,7 @@ void writeAnyEscapedString(const char * begin, const char * end, WriteBuffer & b /// On purpose we will escape more characters than minimally necessary. const char * next_pos = find_first_symbols<'\b', '\f', '\n', '\r', '\t', '\0', '\\', quote_character>(pos, end); + /// NOLINTBEGIN(readability-else-after-return) if (next_pos == end) { buf.write(pos, next_pos - pos); @@ -372,6 +373,7 @@ void writeAnyEscapedString(const char * begin, const char * end, WriteBuffer & b } ++pos; } + /// NOLINTEND(readability-else-after-return) } } @@ -683,12 +685,11 @@ void writeCSVString(const char * begin, const char * end, WriteBuffer & buf) buf.write(pos, end - pos); break; } - else /// Quotation. - { - ++next_pos; - buf.write(pos, next_pos - pos); - writeChar(quote, buf); - } + + /// Quotation. + ++next_pos; + buf.write(pos, next_pos - pos); + writeChar(quote, buf); pos = next_pos; } @@ -720,7 +721,7 @@ inline void writeXMLStringForTextElementOrAttributeValue(const char * begin, con buf.write(pos, end - pos); break; } - else if (*next_pos == '<') + if (*next_pos == '<') { buf.write(pos, next_pos - pos); ++next_pos; @@ -774,7 +775,7 @@ inline void writeXMLStringForTextElement(const char * begin, const char * end, W buf.write(pos, end - pos); break; } - else if (*next_pos == '<') + if (*next_pos == '<') { buf.write(pos, next_pos - pos); ++next_pos; @@ -1088,12 +1089,12 @@ void writeDecimalFractional(const T & x, UInt32 scale, WriteBuffer & ostr, bool writeDecimalFractional(static_cast(x), scale, ostr, trailing_zeros, fixed_fractional_length, fractional_length); return; } - else if (x <= std::numeric_limits::max()) + if (x <= std::numeric_limits::max()) { writeDecimalFractional(static_cast(x), scale, ostr, trailing_zeros, fixed_fractional_length, fractional_length); return; } - else if (x <= std::numeric_limits::max()) + if (x <= std::numeric_limits::max()) { writeDecimalFractional(static_cast(x), scale, ostr, trailing_zeros, fixed_fractional_length, fractional_length); return; @@ -1106,7 +1107,7 @@ void writeDecimalFractional(const T & x, UInt32 scale, WriteBuffer & ostr, bool writeDecimalFractional(static_cast(x), scale, ostr, trailing_zeros, fixed_fractional_length, fractional_length); return; } - else if (x <= std::numeric_limits::max()) + if (x <= std::numeric_limits::max()) { writeDecimalFractional(static_cast(x), scale, ostr, trailing_zeros, fixed_fractional_length, fractional_length); return; diff --git a/src/IO/ZlibInflatingReadBuffer.cpp b/src/IO/ZlibInflatingReadBuffer.cpp index b43dda1bfcc..6e416f6e7ff 100644 --- a/src/IO/ZlibInflatingReadBuffer.cpp +++ b/src/IO/ZlibInflatingReadBuffer.cpp @@ -95,17 +95,12 @@ bool ZlibInflatingReadBuffer::nextImpl() return !working_buffer.empty(); } /// If it is not end of file, we need to reset zstr and return true, because we still have some data to read - else - { - rc = inflateReset(&zstr); - if (rc != Z_OK) - throw Exception( - ErrorCodes::ZLIB_INFLATE_FAILED, - "inflateReset failed: {}{}", - zError(rc), - getExceptionEntryWithFileName(*in)); - return true; - } + + rc = inflateReset(&zstr); + if (rc != Z_OK) + throw Exception( + ErrorCodes::ZLIB_INFLATE_FAILED, "inflateReset failed: {}{}", zError(rc), getExceptionEntryWithFileName(*in)); + return true; } /// If it is not end and not OK, something went wrong, throw exception diff --git a/src/IO/ZstdDeflatingAppendableWriteBuffer.cpp b/src/IO/ZstdDeflatingAppendableWriteBuffer.cpp index 81be8d8ce4d..28486341540 100644 --- a/src/IO/ZstdDeflatingAppendableWriteBuffer.cpp +++ b/src/IO/ZstdDeflatingAppendableWriteBuffer.cpp @@ -210,12 +210,13 @@ bool ZstdDeflatingAppendableWriteBuffer::isNeedToAddEmptyBlock() /// But in this case file still corrupted and we have to remove it. return result != ZSTD_CORRECT_TERMINATION_LAST_BLOCK; } - else if (fsize > 0) + if (fsize > 0) { throw Exception( ErrorCodes::ZSTD_ENCODER_FAILED, "Trying to write to non-empty file '{}' with tiny size {}. It can lead to data corruption", - out->getFileName(), fsize); + out->getFileName(), + fsize); } return false; } diff --git a/src/IO/parseDateTimeBestEffort.cpp b/src/IO/parseDateTimeBestEffort.cpp index 52bcdc6bbb4..27a45fa9ce9 100644 --- a/src/IO/parseDateTimeBestEffort.cpp +++ b/src/IO/parseDateTimeBestEffort.cpp @@ -178,7 +178,7 @@ ReturnType parseDateTimeBestEffortImpl( } return ReturnType(true); } - else if (num_digits == 10 && !year && !has_time) + if (num_digits == 10 && !year && !has_time) { if (strict) return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Strict best effort parsing doesn't allow timestamps"); @@ -187,7 +187,7 @@ ReturnType parseDateTimeBestEffortImpl( readDecimalNumber<10>(res, digits); return ReturnType(true); } - else if (num_digits == 9 && !year && !has_time) + if (num_digits == 9 && !year && !has_time) { if (strict) return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Strict best effort parsing doesn't allow timestamps"); @@ -196,10 +196,11 @@ ReturnType parseDateTimeBestEffortImpl( readDecimalNumber<9>(res, digits); return ReturnType(true); } - else if (num_digits == 14 && !year && !has_time) + if (num_digits == 14 && !year && !has_time) { if (strict) - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Strict best effort parsing doesn't allow date times without separators"); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, "Strict best effort parsing doesn't allow date times without separators"); /// This is YYYYMMDDhhmmss readDecimalNumber<4>(year, digits); @@ -213,7 +214,8 @@ ReturnType parseDateTimeBestEffortImpl( else if (num_digits == 8 && !year) { if (strict) - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Strict best effort parsing doesn't allow date times without separators"); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, "Strict best effort parsing doesn't allow date times without separators"); /// This is YYYYMMDD readDecimalNumber<4>(year, digits); @@ -223,7 +225,8 @@ ReturnType parseDateTimeBestEffortImpl( else if (num_digits == 6) { if (strict) - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Strict best effort parsing doesn't allow date times without separators"); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, "Strict best effort parsing doesn't allow date times without separators"); /// This is YYYYMM or hhmmss if (!year && !month) @@ -239,7 +242,8 @@ ReturnType parseDateTimeBestEffortImpl( has_time = true; } else - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: ambiguous 6 digits, it can be YYYYMM or hhmmss"); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: ambiguous 6 digits, it can be YYYYMM or hhmmss"); } else if (num_digits == 4 && !year) { @@ -256,11 +260,8 @@ ReturnType parseDateTimeBestEffortImpl( { char delimiter_after_year = *in.position(); - if (delimiter_after_year < 0x20 - || delimiter_after_year == ',' - || delimiter_after_year == ';' - || delimiter_after_year == '\'' - || delimiter_after_year == '"') + if (delimiter_after_year < 0x20 || delimiter_after_year == ',' || delimiter_after_year == ';' + || delimiter_after_year == '\'' || delimiter_after_year == '"') break; if (month) @@ -277,7 +278,10 @@ ReturnType parseDateTimeBestEffortImpl( else if (delimiter_after_year == ' ') continue; else - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected number of decimal digits after year: {}", num_digits); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, + "Cannot read DateTime: unexpected number of decimal digits after year: {}", + num_digits); /// Only the same delimiter. if (!day_of_month && checkChar(delimiter_after_year, in)) @@ -291,11 +295,17 @@ ReturnType parseDateTimeBestEffortImpl( else if (delimiter_after_year == ' ') continue; else - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected number of decimal digits after year and month: {}", num_digits); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, + "Cannot read DateTime: unexpected number of decimal digits after year and month: {}", + num_digits); } if (!isSymbolIn(delimiter_after_year, allowed_date_delimiters)) - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: '{}' delimiter between date parts is not allowed", delimiter_after_year); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, + "Cannot read DateTime: '{}' delimiter between date parts is not allowed", + delimiter_after_year); } } else if (num_digits == 2 || num_digits == 1) @@ -334,7 +344,10 @@ ReturnType parseDateTimeBestEffortImpl( else if (num_digits == 1) readDecimalNumber<1>(minute, digits); else - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected number of decimal digits after hour: {}", num_digits); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, + "Cannot read DateTime: unexpected number of decimal digits after hour: {}", + num_digits); if (checkChar(':', in)) { @@ -345,7 +358,10 @@ ReturnType parseDateTimeBestEffortImpl( else if (num_digits == 1) readDecimalNumber<1>(second, digits); else - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected number of decimal digits after hour and minute: {}", num_digits); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, + "Cannot read DateTime: unexpected number of decimal digits after hour and minute: {}", + num_digits); } } else if (checkChar(',', in)) @@ -353,7 +369,9 @@ ReturnType parseDateTimeBestEffortImpl( if (month && !day_of_month) day_of_month = hour_or_day_of_month_or_month; } - else if ((!in.eof() && isSymbolIn(*in.position(), allowed_date_delimiters)) && (checkChar('/', in) || checkChar('.', in) || checkChar('-', in))) + else if ( + (!in.eof() && isSymbolIn(*in.position(), allowed_date_delimiters)) + && (checkChar('/', in) || checkChar('.', in) || checkChar('-', in))) { if (day_of_month) return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: day of month is duplicated"); @@ -370,7 +388,10 @@ ReturnType parseDateTimeBestEffortImpl( else if (num_digits == 1) readDecimalNumber<1>(day_of_month, digits); else - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected number of decimal digits after month: {}", num_digits); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, + "Cannot read DateTime: unexpected number of decimal digits after month: {}", + num_digits); } else { @@ -384,25 +405,35 @@ ReturnType parseDateTimeBestEffortImpl( readDecimalNumber<1>(month, digits); else if (num_digits == 0) { - /// Month in alphabetical form + /// Month in alphabetical form - char alpha[9]; /// The longest month name: September - size_t num_alpha = readAlpha(alpha, sizeof(alpha), in); + char alpha[9]; /// The longest month name: September + size_t num_alpha = readAlpha(alpha, sizeof(alpha), in); - if (num_alpha < 3) - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected number of alphabetical characters after day of month: {}", num_alpha); + if (num_alpha < 3) + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, + "Cannot read DateTime: unexpected number of alphabetical characters after day of month: {}", + num_alpha); - if (!read_alpha_month(alpha)) - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: alphabetical characters after day of month don't look like month: {}", std::string(alpha, 3)); + if (!read_alpha_month(alpha)) + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, + "Cannot read DateTime: alphabetical characters after day of month don't look like month: {}", + std::string(alpha, 3)); } else - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected number of decimal digits after day of month: {}", num_digits); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, + "Cannot read DateTime: unexpected number of decimal digits after day of month: {}", + num_digits); } if (month > 12) std::swap(month, day_of_month); - if ((!in.eof() && isSymbolIn(*in.position(), allowed_date_delimiters)) && (checkChar('/', in) || checkChar('.', in) || checkChar('-', in))) + if ((!in.eof() && isSymbolIn(*in.position(), allowed_date_delimiters)) + && (checkChar('/', in) || checkChar('.', in) || checkChar('-', in))) { if (year) return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: year component is duplicated"); @@ -421,7 +452,10 @@ ReturnType parseDateTimeBestEffortImpl( year += 2000; } else - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected number of decimal digits after day of month and month: {}", num_digits); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, + "Cannot read DateTime: unexpected number of decimal digits after day of month and month: {}", + num_digits); } } else @@ -440,7 +474,8 @@ ReturnType parseDateTimeBestEffortImpl( } } else if (num_digits != 0) - return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected number of decimal digits: {}", num_digits); + return on_error( + ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected number of decimal digits: {}", num_digits); } if (num_digits == 0) @@ -551,11 +586,11 @@ ReturnType parseDateTimeBestEffortImpl( { break; } - else if (num_alpha == 1) + if (num_alpha == 1) { return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected alphabetical character"); } - else if (num_alpha == 2) + if (num_alpha == 2) { if (alpha[1] == 'M' || alpha[1] == 'm') { @@ -580,18 +615,35 @@ ReturnType parseDateTimeBestEffortImpl( if (read_alpha_month(alpha)) { } - else if (0 == strncasecmp(alpha, "UTC", 3)) has_time_zone_offset = true; // NOLINT - else if (0 == strncasecmp(alpha, "GMT", 3)) has_time_zone_offset = true; - else if (0 == strncasecmp(alpha, "MSK", 3)) { has_time_zone_offset = true; time_zone_offset_hour = 3; } - else if (0 == strncasecmp(alpha, "MSD", 3)) { has_time_zone_offset = true; time_zone_offset_hour = 4; } + else if (0 == strncasecmp(alpha, "UTC", 3)) + has_time_zone_offset = true; // NOLINT + else if (0 == strncasecmp(alpha, "GMT", 3)) + has_time_zone_offset = true; + else if (0 == strncasecmp(alpha, "MSK", 3)) + { + has_time_zone_offset = true; + time_zone_offset_hour = 3; + } + else if (0 == strncasecmp(alpha, "MSD", 3)) + { + has_time_zone_offset = true; + time_zone_offset_hour = 4; + } - else if (0 == strncasecmp(alpha, "Mon", 3)) has_day_of_week = true; // NOLINT - else if (0 == strncasecmp(alpha, "Tue", 3)) has_day_of_week = true; - else if (0 == strncasecmp(alpha, "Wed", 3)) has_day_of_week = true; - else if (0 == strncasecmp(alpha, "Thu", 3)) has_day_of_week = true; - else if (0 == strncasecmp(alpha, "Fri", 3)) has_day_of_week = true; - else if (0 == strncasecmp(alpha, "Sat", 3)) has_day_of_week = true; - else if (0 == strncasecmp(alpha, "Sun", 3)) has_day_of_week = true; + else if (0 == strncasecmp(alpha, "Mon", 3)) + has_day_of_week = true; // NOLINT + else if (0 == strncasecmp(alpha, "Tue", 3)) + has_day_of_week = true; + else if (0 == strncasecmp(alpha, "Wed", 3)) + has_day_of_week = true; + else if (0 == strncasecmp(alpha, "Thu", 3)) + has_day_of_week = true; + else if (0 == strncasecmp(alpha, "Fri", 3)) + has_day_of_week = true; + else if (0 == strncasecmp(alpha, "Sat", 3)) + has_day_of_week = true; + else if (0 == strncasecmp(alpha, "Sun", 3)) + has_day_of_week = true; else return on_error(ErrorCodes::CANNOT_PARSE_DATETIME, "Cannot read DateTime: unexpected word"); @@ -653,9 +705,9 @@ ReturnType parseDateTimeBestEffortImpl( { if ((month_ == 1 || month_ == 3 || month_ == 5 || month_ == 7 || month_ == 8 || month_ == 10 || month_ == 12) && day_ >= 1 && day_ <= 31) return true; - else if (month_ == 2 && ((is_leap_year_ && day_ >= 1 && day_ <= 29) || (!is_leap_year_ && day_ >= 1 && day_ <= 28))) + if (month_ == 2 && ((is_leap_year_ && day_ >= 1 && day_ <= 29) || (!is_leap_year_ && day_ >= 1 && day_ <= 28))) return true; - else if ((month_ == 4 || month_ == 6 || month_ == 9 || month_ == 11) && day_ >= 1 && day_ <= 30) + if ((month_ == 4 || month_ == 6 || month_ == 9 || month_ == 11) && day_ >= 1 && day_ <= 30) return true; return false; }; diff --git a/src/IO/readDecimalText.h b/src/IO/readDecimalText.h index f3b08065696..0e9a8beae21 100644 --- a/src/IO/readDecimalText.h +++ b/src/IO/readDecimalText.h @@ -90,28 +90,27 @@ inline bool readDigits(ReadBuffer & buf, T & x, uint32_t & digits, int32_t & exp /// Simply cut excessive digits. break; } - else - { - if constexpr (_throw_on_error) - throw Exception(ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Too many digits ({} > {}) in decimal value", - std::to_string(digits + places), std::to_string(max_digits)); - return false; - } + if constexpr (_throw_on_error) + throw Exception( + ErrorCodes::ARGUMENT_OUT_OF_BOUND, + "Too many digits ({} > {}) in decimal value", + std::to_string(digits + places), + std::to_string(max_digits)); + + return false; } - else - { - digits += places; - if (after_point) - exponent -= places; - // TODO: accurate shift10 for big integers - x *= intExp10OfSize(places); - places = 0; + digits += places; + if (after_point) + exponent -= places; - x += (byte - '0'); - break; - } + // TODO: accurate shift10 for big integers + x *= intExp10OfSize(places); + places = 0; + + x += (byte - '0'); + break; } case 'e': [[fallthrough]]; case 'E': @@ -186,15 +185,13 @@ inline ReturnType readDecimalText(ReadBuffer & buf, T & x, uint32_t precision, u scale = 0; return ReturnType(true); } - else - { - /// Too many digits after point. Just cut off excessive digits. - auto divisor = intExp10OfSize(divisor_exp); - assert(divisor > 0); /// This is for Clang Static Analyzer. It is not smart enough to infer it automatically. - x.value /= divisor; - scale = 0; - return ReturnType(true); - } + + /// Too many digits after point. Just cut off excessive digits. + auto divisor = intExp10OfSize(divisor_exp); + assert(divisor > 0); /// This is for Clang Static Analyzer. It is not smart enough to infer it automatically. + x.value /= divisor; + scale = 0; + return ReturnType(true); } scale += exponent; diff --git a/src/IO/readFloatText.h b/src/IO/readFloatText.h index 215bb1a3270..c2fec9d4b0b 100644 --- a/src/IO/readFloatText.h +++ b/src/IO/readFloatText.h @@ -145,6 +145,7 @@ ReturnType readFloatTextPreciseImpl(T & x, ReadBuffer & buf) static constexpr bool throw_exception = std::is_same_v; static constexpr int MAX_LENGTH = 316; + /// NOLINTBEGIN(readability-else-after-return) ReadBufferFromMemory * buf_from_memory = dynamic_cast(&buf); /// Fast path (avoid copying) if the buffer have at least MAX_LENGTH bytes or buf is ReadBufferFromMemory if (likely(!buf.eof() && (buf_from_memory || buf.position() + MAX_LENGTH <= buf.buffer().end()))) @@ -259,6 +260,7 @@ ReturnType readFloatTextPreciseImpl(T & x, ReadBuffer & buf) return ReturnType(true); } + /// NOLINTEND(readability-else-after-return) } @@ -479,7 +481,7 @@ ReturnType readFloatTextFastImpl(T & x, ReadBuffer & in, bool & has_fractional) } return ReturnType(false); } - else if (*in.position() == 'n' || *in.position() == 'N') + if (*in.position() == 'n' || *in.position() == 'N') { if (assertOrParseNaN(in)) { diff --git a/src/Interpreters/ActionsVisitor.cpp b/src/Interpreters/ActionsVisitor.cpp index 980222849e2..65c3fe8cfcf 100644 --- a/src/Interpreters/ActionsVisitor.cpp +++ b/src/Interpreters/ActionsVisitor.cpp @@ -100,7 +100,7 @@ static size_t getTypeDepth(const DataTypePtr & type) { if (const auto * array_type = typeid_cast(type.get())) return 1 + getTypeDepth(array_type->getNestedType()); - else if (const auto * tuple_type = typeid_cast(type.get())) + if (const auto * tuple_type = typeid_cast(type.get())) return 1 + (tuple_type->getElements().empty() ? 0 : getTypeDepth(tuple_type->getElements().at(0))); return 0; @@ -181,13 +181,12 @@ static Field extractValueFromNode(const ASTPtr & node, const IDataType & type, C { return convertFieldToType(lit->value, type); } - else if (node->as()) + if (node->as()) { std::pair value_raw = evaluateConstantExpression(node, context); return convertFieldToType(value_raw.first, type, value_raw.second.get()); } - else - throw Exception(ErrorCodes::INCORRECT_ELEMENT_OF_SET, "Incorrect element of set. Must be literal or constant expression."); + throw Exception(ErrorCodes::INCORRECT_ELEMENT_OF_SET, "Incorrect element of set. Must be literal or constant expression."); } static Block createBlockFromAST(const ASTPtr & node, const DataTypes & types, ContextPtr context) @@ -1064,14 +1063,13 @@ void ActionsMatcher::visit(const ASTFunction & node, const ASTPtr & ast, Data & // aggregate functions. return; } - else if (node.compute_after_window_functions) + if (node.compute_after_window_functions) { if (!data.build_expression_with_window_functions) { for (const auto & arg : node.arguments->children) { - if (auto const * function = arg->as(); - function && function->name == "lambda") + if (auto const * function = arg->as(); function && function->name == "lambda") { // Lambda function is a special case. It shouldn't be visited here. continue; @@ -1492,16 +1490,13 @@ FutureSetPtr ActionsMatcher::makeSet(const ASTFunction & node, Data & data, bool return data.prepared_sets->addFromSubquery( set_key, std::move(source), nullptr, std::move(external_table_set), data.getContext()->getSettingsRef()); } - else - { - const auto & last_actions = data.actions_stack.getLastActions(); - const auto & index = data.actions_stack.getLastActionsIndex(); - if (data.prepared_sets && index.contains(left_in_operand->getColumnName())) - /// An explicit enumeration of values in parentheses. - return makeExplicitSet(&node, last_actions, data.getContext(), *data.prepared_sets); - else - return {}; - } + + const auto & last_actions = data.actions_stack.getLastActions(); + const auto & index = data.actions_stack.getLastActionsIndex(); + if (data.prepared_sets && index.contains(left_in_operand->getColumnName())) + /// An explicit enumeration of values in parentheses. + return makeExplicitSet(&node, last_actions, data.getContext(), *data.prepared_sets); + return {}; } } diff --git a/src/Interpreters/Aggregator.cpp b/src/Interpreters/Aggregator.cpp index aff06c490c5..0fe1c74ed17 100644 --- a/src/Interpreters/Aggregator.cpp +++ b/src/Interpreters/Aggregator.cpp @@ -640,8 +640,7 @@ AggregatedDataVariants::Type Aggregator::chooseAggregationMethod() { if (has_low_cardinality) return AggregatedDataVariants::Type::low_cardinality_key_fixed_string; - else - return AggregatedDataVariants::Type::key_fixed_string; + return AggregatedDataVariants::Type::key_fixed_string; } /// If all keys fits in N bits, will use hash table with all keys packed (placed contiguously) to single N-bit key. @@ -672,8 +671,7 @@ AggregatedDataVariants::Type Aggregator::chooseAggregationMethod() { if (has_low_cardinality) return AggregatedDataVariants::Type::low_cardinality_key_string; - else - return AggregatedDataVariants::Type::key_string; + return AggregatedDataVariants::Type::key_string; } if (params.keys_size > 1 && all_keys_are_numbers_or_strings) @@ -1975,14 +1973,13 @@ Aggregator::ConvertToBlockResVariant Aggregator::convertToBlockImplFinal( { return insertResultsIntoColumns(places, std::move(out_cols.value()), arena, has_null_key_data, use_compiled_functions); } - else + + if (out_cols.has_value()) { - if (out_cols.has_value()) - { - blocks.emplace_back(insertResultsIntoColumns(places, std::move(out_cols.value()), arena, has_null_key_data, use_compiled_functions)); - } - return blocks; + blocks.emplace_back( + insertResultsIntoColumns(places, std::move(out_cols.value()), arena, has_null_key_data, use_compiled_functions)); } + return blocks; } template @@ -2050,12 +2047,10 @@ Aggregator::convertToBlockImplNotFinal(Method & method, Table & data, Arenas & a { return finalizeBlock(params, getHeader(final), std::move(out_cols).value(), final, rows_in_current_block); } - else - { - if (rows_in_current_block) - res_blocks.emplace_back(finalizeBlock(params, getHeader(final), std::move(out_cols).value(), final, rows_in_current_block)); - return res_blocks; - } + + if (rows_in_current_block) + res_blocks.emplace_back(finalizeBlock(params, getHeader(final), std::move(out_cols).value(), final, rows_in_current_block)); + return res_blocks; } void Aggregator::addSingleKeyToAggregateColumns( diff --git a/src/Interpreters/ArithmeticOperationsInAgrFuncOptimize.cpp b/src/Interpreters/ArithmeticOperationsInAgrFuncOptimize.cpp index ef3e6739f8a..4574620cbb6 100644 --- a/src/Interpreters/ArithmeticOperationsInAgrFuncOptimize.cpp +++ b/src/Interpreters/ArithmeticOperationsInAgrFuncOptimize.cpp @@ -106,10 +106,9 @@ ASTPtr tryExchangeFunctions(const ASTFunction & func) { if (aggregate_function_name == "min") return "max"; - else if (aggregate_function_name == "max") + if (aggregate_function_name == "max") return "min"; - else - return aggregate_function_name; + return aggregate_function_name; }; if (first_literal && !second_literal) diff --git a/src/Interpreters/ArrayJoinAction.cpp b/src/Interpreters/ArrayJoinAction.cpp index bdec5d1025e..f1952a21760 100644 --- a/src/Interpreters/ArrayJoinAction.cpp +++ b/src/Interpreters/ArrayJoinAction.cpp @@ -25,24 +25,22 @@ std::shared_ptr getArrayJoinDataType(DataTypePtr type) { if (const auto * array_type = typeid_cast(type.get())) return std::shared_ptr{type, array_type}; - else if (const auto * map_type = typeid_cast(type.get())) + if (const auto * map_type = typeid_cast(type.get())) { const auto & nested_type = map_type->getNestedType(); const auto * nested_array_type = typeid_cast(nested_type.get()); return std::shared_ptr{nested_type, nested_array_type}; } - else - return nullptr; + return nullptr; } ColumnPtr getArrayJoinColumn(const ColumnPtr & column) { if (typeid_cast(column.get())) return column; - else if (const auto * map = typeid_cast(column.get())) + if (const auto * map = typeid_cast(column.get())) return map->getNestedColumnPtr(); - else - return nullptr; + return nullptr; } const ColumnArray * getArrayJoinColumnRawPtr(const ColumnPtr & column) diff --git a/src/Interpreters/AsynchronousInsertQueue.cpp b/src/Interpreters/AsynchronousInsertQueue.cpp index afd0508829f..5cc97effad6 100644 --- a/src/Interpreters/AsynchronousInsertQueue.cpp +++ b/src/Interpreters/AsynchronousInsertQueue.cpp @@ -580,7 +580,7 @@ AsynchronousInsertQueue::Milliseconds AsynchronousInsertQueue::getBusyWaitTimeou /// that is, if the time since the last insert and the difference between the last two queue flushes were both /// long enough (exceeding the adjusted timeout). /// This ensures the timeout value converges to the minimum over time for non-frequent inserts. - else if (last_insert_time + decreased_timeout_ms < now && t1 + decreased_timeout_ms < t2) + if (last_insert_time + decreased_timeout_ms < now && t1 + decreased_timeout_ms < t2) return normalize(decreased_timeout_ms); return normalize(shard.busy_timeout_ms); diff --git a/src/Interpreters/AsynchronousInsertQueue.h b/src/Interpreters/AsynchronousInsertQueue.h index eb4e1ed471c..2bc9d5e2fe7 100644 --- a/src/Interpreters/AsynchronousInsertQueue.h +++ b/src/Interpreters/AsynchronousInsertQueue.h @@ -118,8 +118,7 @@ private: { if (std::holds_alternative(*this)) return DataKind::Preprocessed; - else - return DataKind::Parsed; + return DataKind::Parsed; } bool empty() const diff --git a/src/Interpreters/BloomFilter.cpp b/src/Interpreters/BloomFilter.cpp index 7bf50a0312b..e03eff583aa 100644 --- a/src/Interpreters/BloomFilter.cpp +++ b/src/Interpreters/BloomFilter.cpp @@ -127,8 +127,7 @@ DataTypePtr BloomFilter::getPrimitiveType(const DataTypePtr & data_type) { if (!typeid_cast(array_type->getNestedType().get())) return getPrimitiveType(array_type->getNestedType()); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unexpected type {} of bloom filter index.", data_type->getName()); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unexpected type {} of bloom filter index.", data_type->getName()); } if (const auto * nullable_type = typeid_cast(data_type.get())) diff --git a/src/Interpreters/BloomFilterHash.h b/src/Interpreters/BloomFilterHash.h index 49450b5932b..bd3f9568dbc 100644 --- a/src/Interpreters/BloomFilterHash.h +++ b/src/Interpreters/BloomFilterHash.h @@ -75,30 +75,54 @@ struct BloomFilterHash WhichDataType which(data_type); if (which.isUInt8()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isUInt16()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isUInt32()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isUInt64()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isUInt128()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isUInt256()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isInt8()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isInt16()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isInt32()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isInt64()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isInt128()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isInt256()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isEnum8()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isEnum16()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isDate()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isDate32()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isDateTime()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isFloat32()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isFloat64()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isUUID()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isIPv4()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isIPv6()) return build_hash_column(getNumberTypeHash(field)); - else if (which.isString()) return build_hash_column(getStringTypeHash(field)); - else if (which.isFixedString()) return build_hash_column(getFixedStringTypeHash(field, data_type)); - else throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unexpected type {} of bloom filter index.", data_type->getName()); + if (which.isUInt16()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isUInt32()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isUInt64()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isUInt128()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isUInt256()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isInt8()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isInt16()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isInt32()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isInt64()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isInt128()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isInt256()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isEnum8()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isEnum16()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isDate()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isDate32()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isDateTime()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isFloat32()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isFloat64()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isUUID()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isIPv4()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isIPv6()) + return build_hash_column(getNumberTypeHash(field)); + if (which.isString()) + return build_hash_column(getStringTypeHash(field)); + if (which.isFixedString()) + return build_hash_column(getFixedStringTypeHash(field, data_type)); + + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unexpected type {} of bloom filter index.", data_type->getName()); } static ColumnPtr hashWithColumn(const DataTypePtr & data_type, const ColumnPtr & column, size_t pos, size_t limit) diff --git a/src/Interpreters/Cache/EvictionCandidates.cpp b/src/Interpreters/Cache/EvictionCandidates.cpp index 82214c98376..08776ad5aee 100644 --- a/src/Interpreters/Cache/EvictionCandidates.cpp +++ b/src/Interpreters/Cache/EvictionCandidates.cpp @@ -242,8 +242,7 @@ void EvictionCandidates::setSpaceHolder( { if (hold_space) throw Exception(ErrorCodes::LOGICAL_ERROR, "Space hold is already set"); - else - hold_space = std::make_unique(size, elements, priority, lock); + hold_space = std::make_unique(size, elements, priority, lock); } } diff --git a/src/Interpreters/Cache/LRUFileCachePriority.cpp b/src/Interpreters/Cache/LRUFileCachePriority.cpp index 0e0170c76e3..a89f689c7c7 100644 --- a/src/Interpreters/Cache/LRUFileCachePriority.cpp +++ b/src/Interpreters/Cache/LRUFileCachePriority.cpp @@ -317,10 +317,8 @@ bool LRUFileCachePriority::collectCandidatesForEviction( return true; } - else - { - return false; - } + + return false; } IFileCachePriority::CollectStatus LRUFileCachePriority::collectCandidatesForEviction( diff --git a/src/Interpreters/Cache/Metadata.cpp b/src/Interpreters/Cache/Metadata.cpp index 981c1052d01..2ee985b1c31 100644 --- a/src/Interpreters/Cache/Metadata.cpp +++ b/src/Interpreters/Cache/Metadata.cpp @@ -205,13 +205,9 @@ String CacheMetadata::getKeyPath(const Key & key, const UserInfo & user) const { const auto key_str = key.toString(); if (write_cache_per_user_directory) - { return fs::path(path) / fmt::format("{}.{}", user.user_id, user.weight.value()) / key_str.substr(0, 3) / key_str; - } - else - { - return fs::path(path) / key_str.substr(0, 3) / key_str; - } + + return fs::path(path) / key_str.substr(0, 3) / key_str; } CacheMetadataGuard::Lock CacheMetadata::MetadataBucket::lock() const @@ -245,7 +241,7 @@ LockedKeyPtr CacheMetadata::lockKeyMetadata( if (key_not_found_policy == KeyNotFoundPolicy::THROW) throw Exception(ErrorCodes::BAD_ARGUMENTS, "No such key `{}` in cache", key); - else if (key_not_found_policy == KeyNotFoundPolicy::THROW_LOGICAL) + if (key_not_found_policy == KeyNotFoundPolicy::THROW_LOGICAL) throw Exception(ErrorCodes::LOGICAL_ERROR, "No such key `{}` in cache", key); if (key_not_found_policy == KeyNotFoundPolicy::RETURN_NULL) @@ -282,9 +278,9 @@ KeyMetadataPtr CacheMetadata::getKeyMetadata( { if (key_not_found_policy == KeyNotFoundPolicy::THROW) throw Exception(ErrorCodes::BAD_ARGUMENTS, "No such key `{}` in cache", key); - else if (key_not_found_policy == KeyNotFoundPolicy::THROW_LOGICAL) + if (key_not_found_policy == KeyNotFoundPolicy::THROW_LOGICAL) throw Exception(ErrorCodes::LOGICAL_ERROR, "No such key `{}` in cache", key); - else if (key_not_found_policy == KeyNotFoundPolicy::RETURN_NULL) + if (key_not_found_policy == KeyNotFoundPolicy::RETURN_NULL) return nullptr; it = bucket.emplace( @@ -321,7 +317,7 @@ void CacheMetadata::iterate(IterateFunc && func, const KeyMetadata::UserID & use func(*locked_key); continue; } - else if (key_state == KeyMetadata::KeyState::REMOVING) + if (key_state == KeyMetadata::KeyState::REMOVING) continue; throw Exception( @@ -364,8 +360,7 @@ void CacheMetadata::removeKey(const Key & key, bool if_exists, bool if_releasabl { if (if_exists) return; - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "No such key: {}", key); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "No such key: {}", key); } it->second->assertAccess(user_id); @@ -375,9 +370,7 @@ void CacheMetadata::removeKey(const Key & key, bool if_exists, bool if_releasabl { if (if_exists) return; - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, - "No such key: {} (state: {})", key, magic_enum::enum_name(state)); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "No such key: {} (state: {})", key, magic_enum::enum_name(state)); } bool removed_all = locked_key->removeAllFileSegments(if_releasable); @@ -889,7 +882,7 @@ bool LockedKey::removeAllFileSegments(bool if_releasable) removed_all = false; continue; } - else if (it->second->isEvictingOrRemoved(*this)) + if (it->second->isEvictingOrRemoved(*this)) { /// File segment is currently a removal candidate, /// we do not know if it will be removed or not yet, diff --git a/src/Interpreters/Cache/SLRUFileCachePriority.cpp b/src/Interpreters/Cache/SLRUFileCachePriority.cpp index f5ea519d7d4..41e15836a0d 100644 --- a/src/Interpreters/Cache/SLRUFileCachePriority.cpp +++ b/src/Interpreters/Cache/SLRUFileCachePriority.cpp @@ -84,11 +84,9 @@ bool SLRUFileCachePriority::canFit( /// NOLINT const auto * slru_iterator = assert_cast(reservee.get()); if (slru_iterator->is_protected) return protected_queue.canFit(size, elements, lock); - else - return probationary_queue.canFit(size, elements, lock); - } - else return probationary_queue.canFit(size, elements, lock); + } + return probationary_queue.canFit(size, elements, lock); } IFileCachePriority::IteratorPtr SLRUFileCachePriority::add( /// NOLINT @@ -308,8 +306,7 @@ IFileCachePriority::CollectStatus SLRUFileCachePriority::collectCandidatesForEvi if (probationary_desired_size_status == CollectStatus::SUCCESS) return protected_desired_size_status; - else - return probationary_desired_size_status; + return probationary_desired_size_status; } void SLRUFileCachePriority::downgrade(IteratorPtr iterator, const CachePriorityGuard::Lock & lock) diff --git a/src/Interpreters/Cache/WriteBufferToFileSegment.cpp b/src/Interpreters/Cache/WriteBufferToFileSegment.cpp index aa7370bd9ce..d453949667e 100644 --- a/src/Interpreters/Cache/WriteBufferToFileSegment.cpp +++ b/src/Interpreters/Cache/WriteBufferToFileSegment.cpp @@ -34,9 +34,9 @@ namespace auto query_context = CurrentThread::getQueryContext(); if (query_context) return query_context->getSettingsRef()[Setting::temporary_data_in_cache_reserve_space_wait_lock_timeout_milliseconds]; - else - return Context::getGlobalContextInstance() - ->getSettingsRef()[Setting::temporary_data_in_cache_reserve_space_wait_lock_timeout_milliseconds]; + + return Context::getGlobalContextInstance() + ->getSettingsRef()[Setting::temporary_data_in_cache_reserve_space_wait_lock_timeout_milliseconds]; } } @@ -142,8 +142,7 @@ std::unique_ptr WriteBufferToFileSegment::getReadBufferImpl() finalize(); if (file_segment->getDownloadedSize() > 0) return std::make_unique(file_segment->getPath()); - else - return std::make_unique(); + return std::make_unique(); } } diff --git a/src/Interpreters/Cluster.cpp b/src/Interpreters/Cluster.cpp index d10ca6d3961..41382137156 100644 --- a/src/Interpreters/Cluster.cpp +++ b/src/Interpreters/Cluster.cpp @@ -226,15 +226,10 @@ String Cluster::Address::toFullString(bool use_compact_format) const return fmt::format("shard{}_replica{}", shard_index, replica_index); } - else - { - return - escapeForFileName(user) - + (password.empty() ? "" : (':' + escapeForFileName(password))) + '@' - + escapeForFileName(host_name) + ':' + std::to_string(port) - + (default_database.empty() ? "" : ('#' + escapeForFileName(default_database))) - + ((secure == Protocol::Secure::Enable) ? "+secure" : ""); - } + + return escapeForFileName(user) + (password.empty() ? "" : (':' + escapeForFileName(password))) + '@' + escapeForFileName(host_name) + + ':' + std::to_string(port) + (default_database.empty() ? "" : ('#' + escapeForFileName(default_database))) + + ((secure == Protocol::Secure::Enable) ? "+secure" : ""); } Cluster::Address Cluster::Address::fromFullString(std::string_view full_string) @@ -271,47 +266,45 @@ Cluster::Address Cluster::Address::fromFullString(std::string_view full_string) return address; } - else + + /// parsing with the old user[:password]@host:port#default_database format + /// This format is appeared to be inconvenient for the following reasons: + /// - credentials are exposed in file name; + /// - the file name can be too long. + + const char * address_begin = full_string.data(); + const char * address_end = address_begin + full_string.size(); + const char * user_pw_end = strchr(address_begin, '@'); + + Protocol::Secure secure = Protocol::Secure::Disable; + const char * secure_tag = "+secure"; + if (full_string.ends_with(secure_tag)) { - /// parsing with the old user[:password]@host:port#default_database format - /// This format is appeared to be inconvenient for the following reasons: - /// - credentials are exposed in file name; - /// - the file name can be too long. - - const char * address_begin = full_string.data(); - const char * address_end = address_begin + full_string.size(); - const char * user_pw_end = strchr(address_begin, '@'); - - Protocol::Secure secure = Protocol::Secure::Disable; - const char * secure_tag = "+secure"; - if (full_string.ends_with(secure_tag)) - { - address_end -= strlen(secure_tag); - secure = Protocol::Secure::Enable; - } - - const char * colon = strchr(full_string.data(), ':'); - if (!user_pw_end || !colon) - throw Exception(ErrorCodes::SYNTAX_ERROR, "Incorrect user[:password]@host:port#default_database format {}", full_string); - - const bool has_pw = colon < user_pw_end; - const char * host_end = has_pw ? strchr(user_pw_end + 1, ':') : colon; - if (!host_end) - throw Exception(ErrorCodes::SYNTAX_ERROR, "Incorrect address '{}', it does not contain port", full_string); - - const char * has_db = strchr(full_string.data(), '#'); - const char * port_end = has_db ? has_db : address_end; - - Address address; - address.secure = secure; - address.port = parse(host_end + 1, port_end - (host_end + 1)); - address.host_name = unescapeForFileName(std::string(user_pw_end + 1, host_end)); - address.user = unescapeForFileName(std::string(address_begin, has_pw ? colon : user_pw_end)); - address.password = has_pw ? unescapeForFileName(std::string(colon + 1, user_pw_end)) : std::string(); - address.default_database = has_db ? unescapeForFileName(std::string(has_db + 1, address_end)) : std::string(); - // address.priority ignored - return address; + address_end -= strlen(secure_tag); + secure = Protocol::Secure::Enable; } + + const char * colon = strchr(full_string.data(), ':'); + if (!user_pw_end || !colon) + throw Exception(ErrorCodes::SYNTAX_ERROR, "Incorrect user[:password]@host:port#default_database format {}", full_string); + + const bool has_pw = colon < user_pw_end; + const char * host_end = has_pw ? strchr(user_pw_end + 1, ':') : colon; + if (!host_end) + throw Exception(ErrorCodes::SYNTAX_ERROR, "Incorrect address '{}', it does not contain port", full_string); + + const char * has_db = strchr(full_string.data(), '#'); + const char * port_end = has_db ? has_db : address_end; + + Address address; + address.secure = secure; + address.port = parse(host_end + 1, port_end - (host_end + 1)); + address.host_name = unescapeForFileName(std::string(user_pw_end + 1, host_end)); + address.user = unescapeForFileName(std::string(address_begin, has_pw ? colon : user_pw_end)); + address.password = has_pw ? unescapeForFileName(std::string(colon + 1, user_pw_end)) : std::string(); + address.default_database = has_db ? unescapeForFileName(std::string(has_db + 1, address_end)) : std::string(); + // address.priority ignored + return address; } @@ -666,8 +659,7 @@ Poco::Timespan Cluster::saturate(Poco::Timespan v, Poco::Timespan limit) { if (limit.totalMicroseconds() == 0) return v; - else - return (v > limit) ? limit : v; + return (v > limit) ? limit : v; } @@ -910,10 +902,8 @@ const std::string & Cluster::ShardInfo::insertPathForInternalReplication(bool pr } return path; } - else - { - return paths.compact; - } + + return paths.compact; } bool Cluster::maybeCrossReplication() const diff --git a/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp b/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp index 1ac7e776f9c..237a652269c 100644 --- a/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp +++ b/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp @@ -270,9 +270,12 @@ void SelectStreamFactory::createForShardImpl( emplace_remote_stream(); return; } - else - throw Exception(ErrorCodes::ALL_REPLICAS_ARE_STALE, "Local replica of shard {} is stale (delay: " - "{}s.), but no other replica configured", shard_info.shard_num, toString(local_delay)); + throw Exception( + ErrorCodes::ALL_REPLICAS_ARE_STALE, + "Local replica of shard {} is stale (delay: " + "{}s.), but no other replica configured", + shard_info.shard_num, + toString(local_delay)); } if (!shard_info.hasRemoteConnections()) diff --git a/src/Interpreters/ComparisonGraph.cpp b/src/Interpreters/ComparisonGraph.cpp index d53ff4b0227..e0257cbc907 100644 --- a/src/Interpreters/ComparisonGraph.cpp +++ b/src/Interpreters/ComparisonGraph.cpp @@ -12,6 +12,8 @@ #include +#include + namespace DB { @@ -226,13 +228,11 @@ ComparisonGraph::ComparisonGraph(const NodeContainer & atomic_formulas, Co return it->second; } - else - { - nodes_graph.node_hash_to_component[Graph::getHash(node)] = nodes_graph.vertices.size(); - nodes_graph.vertices.push_back(EqualComponent{{node}, std::nullopt}); - nodes_graph.edges.emplace_back(); - return nodes_graph.vertices.size() - 1; - } + + nodes_graph.node_hash_to_component[Graph::getHash(node)] = nodes_graph.vertices.size(); + nodes_graph.vertices.push_back(EqualComponent{{node}, std::nullopt}); + nodes_graph.edges.emplace_back(); + return nodes_graph.vertices.size() - 1; }; const auto * function_node = tryGetFunctionNode(atom); @@ -365,11 +365,10 @@ ComparisonGraphCompareResult ComparisonGraph::compare(const Node & left, c return result; } - else - { - start = it_left->second; - finish = it_right->second; - } + + start = it_left->second; + finish = it_right->second; + if (start == finish) return ComparisonGraphCompareResult::EQUAL; @@ -455,8 +454,7 @@ typename ComparisonGraph::NodeContainer ComparisonGraph::getEqual(co const auto res = getComponentId(node); if (!res) return {}; - else - return getComponent(res.value()); + return getComponent(res.value()); } template @@ -481,10 +479,8 @@ std::optional ComparisonGraph::getComponentId(const Node & node) c { return index; } - else - { - return {}; - } + + return {}; } template @@ -748,7 +744,7 @@ std::map, typename ComparisonGraph::Path> Compar for (size_t v = 0; v < n; ++v) for (size_t u = 0; u < n; ++u) if (results[v][k] != inf && results[k][u] != inf) - results[v][u] = std::min(results[v][u], std::min(results[v][k], results[k][u])); + results[v][u] = std::min({results[v][u], results[v][k], results[k][u]}); std::map, Path> path; for (size_t v = 0; v < n; ++v) diff --git a/src/Interpreters/Context.cpp b/src/Interpreters/Context.cpp index 2320af806f0..8402dc74c1e 100644 --- a/src/Interpreters/Context.cpp +++ b/src/Interpreters/Context.cpp @@ -3678,21 +3678,19 @@ bool Context::tryCheckClientConnectionToMyKeeperCluster() const /// Connected, return true return true; } - else - { - Poco::Util::AbstractConfiguration::Keys keys; - getConfigRef().keys("auxiliary_zookeepers", keys); - /// If our server is part of some auxiliary_zookeeper - for (const auto & aux_zk_name : keys) + Poco::Util::AbstractConfiguration::Keys keys; + getConfigRef().keys("auxiliary_zookeepers", keys); + + /// If our server is part of some auxiliary_zookeeper + for (const auto & aux_zk_name : keys) + { + if (checkZooKeeperConfigIsLocal(getConfigRef(), "auxiliary_zookeepers." + aux_zk_name)) { - if (checkZooKeeperConfigIsLocal(getConfigRef(), "auxiliary_zookeepers." + aux_zk_name)) - { - LOG_DEBUG(shared->log, "Our Keeper server is participant of the auxiliary zookeeper cluster ({}), will try to connect to it", aux_zk_name); - getAuxiliaryZooKeeper(aux_zk_name); - /// Connected, return true - return true; - } + LOG_DEBUG(shared->log, "Our Keeper server is participant of the auxiliary zookeeper cluster ({}), will try to connect to it", aux_zk_name); + getAuxiliaryZooKeeper(aux_zk_name); + /// Connected, return true + return true; } } @@ -4010,8 +4008,7 @@ UInt16 Context::getServerPort(const String & port_name) const auto it = shared->server_ports.find(port_name); if (it == shared->server_ports.end()) throw Exception(ErrorCodes::CLUSTER_DOESNT_EXIST, "There is no port named {}", port_name); - else - return it->second; + return it->second; } void Context::setMaxPartNumToWarn(size_t max_part_to_warn) diff --git a/src/Interpreters/DDLTask.cpp b/src/Interpreters/DDLTask.cpp index d3b9d01a981..106710a9bb4 100644 --- a/src/Interpreters/DDLTask.cpp +++ b/src/Interpreters/DDLTask.cpp @@ -417,28 +417,27 @@ bool DDLTask::tryFindHostInCluster() "There are two exactly the same ClickHouse instances {} in cluster {}", address.readableString(), cluster_name); } - else - { - /* Circular replication is used. + + /* Circular replication is used. * It is when every physical node contains * replicas of different shards of the same table. * To distinguish one replica from another on the same node, * every shard is placed into separate database. * */ - is_circular_replicated = true; - auto * query_with_table = dynamic_cast(query.get()); + is_circular_replicated = true; + auto * query_with_table = dynamic_cast(query.get()); - /// For other DDLs like CREATE USER, there is no database name and should be executed successfully. - if (query_with_table) - { - if (!query_with_table->database) - throw Exception(ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION, - "For a distributed DDL on circular replicated cluster its table name " - "must be qualified by database name."); + /// For other DDLs like CREATE USER, there is no database name and should be executed successfully. + if (query_with_table) + { + if (!query_with_table->database) + throw Exception( + ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION, + "For a distributed DDL on circular replicated cluster its table name " + "must be qualified by database name."); - if (default_database == query_with_table->getDatabase()) - return true; - } + if (default_database == query_with_table->getDatabase()) + return true; } } found_exact_match = true; @@ -474,13 +473,11 @@ bool DDLTask::tryFindHostInClusterViaResolving(ContextPtr context) "There are two the same ClickHouse instances in cluster {} : {} and {}", cluster_name, address_in_cluster.readableString(), address.readableString()); } - else - { - found_via_resolving = true; - host_shard_num = shard_num; - host_replica_num = replica_num; - address_in_cluster = address; - } + + found_via_resolving = true; + host_shard_num = shard_num; + host_replica_num = replica_num; + address_in_cluster = address; } } } @@ -618,8 +615,7 @@ ClusterPtr tryGetReplicatedDatabaseCluster(const String & cluster_name) { if (all_groups) return replicated_db->tryGetAllGroupsCluster(); - else - return replicated_db->tryGetCluster(); + return replicated_db->tryGetCluster(); } return {}; } diff --git a/src/Interpreters/DDLWorker.cpp b/src/Interpreters/DDLWorker.cpp index fec8e6c53c1..497ff7d5d07 100644 --- a/src/Interpreters/DDLWorker.cpp +++ b/src/Interpreters/DDLWorker.cpp @@ -398,18 +398,16 @@ void DDLWorker::scheduleTasks(bool reinitialized) bool maybe_concurrently_deleting = task && !zookeeper->exists(fs::path(task->entry_path) / "active"); return task && !maybe_concurrently_deleting && !maybe_currently_processing; } - else if (last_skipped_entry_name.has_value() && !queue_fully_loaded_after_initialization_debug_helper) + if (last_skipped_entry_name.has_value() && !queue_fully_loaded_after_initialization_debug_helper) { /// If connection was lost during queue loading /// we may start processing from finished task (because we don't know yet that it's finished) and it's ok. return false; } - else - { - /// Return true if entry should not be scheduled. - bool processed = !task && reason == TASK_PROCESSED_OUT_REASON; - return processed || maybe_currently_processing; - } + + /// Return true if entry should not be scheduled. + bool processed = !task && reason == TASK_PROCESSED_OUT_REASON; + return processed || maybe_currently_processing; })); for (auto it = begin_node; it != queue_nodes.end() && !stop_flag; ++it) @@ -688,12 +686,10 @@ void DDLWorker::processTask(DDLTaskBase & task, const ZooKeeperPtr & zookeeper) { throw Exception(ErrorCodes::UNFINISHED, "Unexpected error: {}", task.execution_status.message); } - else - { - /// task.ops where not executed by table or database engine, so DDLWorker is responsible for - /// writing query execution status into ZooKeeper. - task.ops.emplace_back(zkutil::makeSetRequest(finished_node_path, task.execution_status.serializeText(), -1)); - } + + /// task.ops where not executed by table or database engine, so DDLWorker is responsible for + /// writing query execution status into ZooKeeper. + task.ops.emplace_back(zkutil::makeSetRequest(finished_node_path, task.execution_status.serializeText(), -1)); } /// We need to distinguish ZK errors occurred before and after query executing @@ -867,7 +863,7 @@ bool DDLWorker::tryExecuteQueryOnLeaderReplica( executed_by_us = true; break; } - else if (extra_attempt_for_replicated_database) + if (extra_attempt_for_replicated_database) break; } @@ -880,22 +876,19 @@ bool DDLWorker::tryExecuteQueryOnLeaderReplica( task.ops.push_back(op); break; } - else + + String tries_count; + zookeeper->tryGet(tries_to_execute_path, tries_count); + if (parse(tries_count) > MAX_TRIES_TO_EXECUTE) { - String tries_count; - zookeeper->tryGet(tries_to_execute_path, tries_count); - if (parse(tries_count) > MAX_TRIES_TO_EXECUTE) - { - /// Nobody will try to execute query again - LOG_WARNING(log, "Maximum retries count for task {} exceeded, cannot execute replicated DDL query", task.entry_name); - break; - } - else - { - /// Will try to wait or execute - LOG_TRACE(log, "Task {} still not executed, will try to wait for it or execute ourselves, tries count {}", task.entry_name, tries_count); - } + /// Nobody will try to execute query again + LOG_WARNING(log, "Maximum retries count for task {} exceeded, cannot execute replicated DDL query", task.entry_name); + break; } + + /// Will try to wait or execute + LOG_TRACE( + log, "Task {} still not executed, will try to wait for it or execute ourselves, tries count {}", task.entry_name, tries_count); } chassert(!(executed_by_us && executed_by_other_leader)); diff --git a/src/Interpreters/DatabaseCatalog.cpp b/src/Interpreters/DatabaseCatalog.cpp index fb4fad85f66..ee20c9452f6 100644 --- a/src/Interpreters/DatabaseCatalog.cpp +++ b/src/Interpreters/DatabaseCatalog.cpp @@ -518,10 +518,12 @@ void DatabaseCatalog::assertDatabaseExists(const String & database_name) const { throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database {} does not exist", backQuoteIfNeed(database_name)); } - else - { - throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database {} does not exist. Maybe you meant {}?", backQuoteIfNeed(database_name), backQuoteIfNeed(names[0])); - } + + throw Exception( + ErrorCodes::UNKNOWN_DATABASE, + "Database {} does not exist. Maybe you meant {}?", + backQuoteIfNeed(database_name), + backQuoteIfNeed(names[0])); } } @@ -578,10 +580,12 @@ DatabasePtr DatabaseCatalog::detachDatabase(ContextPtr local_context, const Stri { throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database {} does not exist", backQuoteIfNeed(database_name)); } - else - { - throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database {} does not exist. Maybe you meant {}?", backQuoteIfNeed(database_name), backQuoteIfNeed(names[0])); - } + + throw Exception( + ErrorCodes::UNKNOWN_DATABASE, + "Database {} does not exist. Maybe you meant {}?", + backQuoteIfNeed(database_name), + backQuoteIfNeed(names[0])); } if (check_empty) { @@ -659,10 +663,12 @@ DatabasePtr DatabaseCatalog::getDatabase(const String & database_name) const { throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database {} does not exist", backQuoteIfNeed(database_name)); } - else - { - throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database {} does not exist. Maybe you meant {}?", backQuoteIfNeed(database_name), backQuoteIfNeed(names[0])); - } + + throw Exception( + ErrorCodes::UNKNOWN_DATABASE, + "Database {} does not exist. Maybe you meant {}?", + backQuoteIfNeed(database_name), + backQuoteIfNeed(names[0])); } return db; } @@ -1723,7 +1729,7 @@ bool DatabaseCatalog::maybeRemoveDirectory(const String & disk_name, const DiskP return false; } - time_t max_modification_time = std::max(st.st_atime, std::max(st.st_mtime, st.st_ctime)); + time_t max_modification_time = std::max({st.st_atime, st.st_mtime, st.st_ctime}); time_t current_time = time(nullptr); if (st.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO)) { @@ -1741,25 +1747,23 @@ bool DatabaseCatalog::maybeRemoveDirectory(const String & disk_name, const DiskP return true; } - else - { - auto unused_dir_rm_timeout_sec = static_cast(getContext()->getServerSettings().database_catalog_unused_dir_rm_timeout_sec); - if (!unused_dir_rm_timeout_sec) - return false; + auto unused_dir_rm_timeout_sec = static_cast(getContext()->getServerSettings().database_catalog_unused_dir_rm_timeout_sec); - if (current_time <= max_modification_time + unused_dir_rm_timeout_sec) - return false; + if (!unused_dir_rm_timeout_sec) + return false; - LOG_INFO(log, "Removing unused directory {} from disk {}", unused_dir, disk_name); + if (current_time <= max_modification_time + unused_dir_rm_timeout_sec) + return false; - /// We have to set these access rights to make recursive removal work - disk->chmod(unused_dir, S_IRWXU); + LOG_INFO(log, "Removing unused directory {} from disk {}", unused_dir, disk_name); - disk->removeRecursive(unused_dir); + /// We have to set these access rights to make recursive removal work + disk->chmod(unused_dir, S_IRWXU); - return true; - } + disk->removeRecursive(unused_dir); + + return true; } catch (...) { diff --git a/src/Interpreters/ExternalLoader.cpp b/src/Interpreters/ExternalLoader.cpp index 511300be2e0..3408a0d57d4 100644 --- a/src/Interpreters/ExternalLoader.cpp +++ b/src/Interpreters/ExternalLoader.cpp @@ -731,10 +731,9 @@ private: { if (object) return isLoading() ? Status::LOADED_AND_RELOADING : Status::LOADED; - else if (exception) + if (exception) return isLoading() ? Status::FAILED_AND_RELOADING : Status::FAILED; - else - return isLoading() ? Status::LOADING : Status::NOT_LOADED; + return isLoading() ? Status::LOADING : Status::NOT_LOADED; } Duration loadingDuration() const @@ -1193,12 +1192,10 @@ private: LOG_TRACE(log, "Supposed update time for '{}' is {} (backoff, {} errors)", loaded_object->getLoadableName(), to_string(result), error_count); return result; } - else - { - auto result = std::chrono::system_clock::now() + std::chrono::seconds(calculateDurationWithBackoff(rnd_engine, error_count)); - LOG_TRACE(log, "Supposed update time for unspecified object is {} (backoff, {} errors)", to_string(result), error_count); - return result; - } + + auto result = std::chrono::system_clock::now() + std::chrono::seconds(calculateDurationWithBackoff(rnd_engine, error_count)); + LOG_TRACE(log, "Supposed update time for unspecified object is {} (backoff, {} errors)", to_string(result), error_count); + return result; } const String type_name; diff --git a/src/Interpreters/GlobalSubqueriesVisitor.h b/src/Interpreters/GlobalSubqueriesVisitor.h index a821a8dcfc2..e1d5f9b62a7 100644 --- a/src/Interpreters/GlobalSubqueriesVisitor.h +++ b/src/Interpreters/GlobalSubqueriesVisitor.h @@ -231,7 +231,7 @@ private: data.getContext()->getQueryContext()->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0)); return; } - else if (settings[Setting::allow_experimental_parallel_reading_from_replicas] >= 2) + if (settings[Setting::allow_experimental_parallel_reading_from_replicas] >= 2) throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "IN with subquery is not supported with parallel replicas"); } } @@ -289,7 +289,7 @@ private: data.getContext()->getQueryContext()->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0)); return; } - else if (settings[Setting::allow_experimental_parallel_reading_from_replicas] >= 2) + if (settings[Setting::allow_experimental_parallel_reading_from_replicas] >= 2) throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "JOIN with parallel replicas is only supported with subqueries"); } } diff --git a/src/Interpreters/HashJoin/HashJoinMethodsImpl.h b/src/Interpreters/HashJoin/HashJoinMethodsImpl.h index 320c8851ce4..45a766e2df6 100644 --- a/src/Interpreters/HashJoin/HashJoinMethodsImpl.h +++ b/src/Interpreters/HashJoin/HashJoinMethodsImpl.h @@ -291,11 +291,9 @@ size_t HashJoinMethods::joinRightColumnsSwitchNu return joinRightColumnsSwitchMultipleDisjuncts( std::forward>(key_getter_vector), mapv, added_columns, used_flags); } - else - { - return joinRightColumnsSwitchMultipleDisjuncts( - std::forward>(key_getter_vector), mapv, added_columns, used_flags); - } + + return joinRightColumnsSwitchMultipleDisjuncts( + std::forward>(key_getter_vector), mapv, added_columns, used_flags); } template @@ -772,8 +770,7 @@ size_t HashJoinMethods::joinRightColumnsWithAddt selected_right_row_it = selected_right_row_it + row_replicate_offset[i] - replicated_row; break; } - else - ++selected_right_row_it; + ++selected_right_row_it; } } } diff --git a/src/Interpreters/IdentifierSemantic.cpp b/src/Interpreters/IdentifierSemantic.cpp index ae5e70d1dcd..5b5f9373009 100644 --- a/src/Interpreters/IdentifierSemantic.cpp +++ b/src/Interpreters/IdentifierSemantic.cpp @@ -144,7 +144,7 @@ std::optional IdentifierSemantic::extractNestedName(const ASTIdentifier { if (identifier.name_parts.size() == 3 && table_name == identifier.name_parts[0]) return identifier.name_parts[1] + '.' + identifier.name_parts[2]; - else if (identifier.name_parts.size() == 2) + if (identifier.name_parts.size() == 2) return identifier.name_parts[0] + '.' + identifier.name_parts[1]; return {}; } @@ -209,8 +209,7 @@ IdentifierSemantic::ColumnMatch IdentifierSemantic::canReferColumnToTable(const { if (!db_and_table.alias.empty()) return ColumnMatch::AliasedTableName; - else - return ColumnMatch::TableName; + return ColumnMatch::TableName; } return ColumnMatch::NoMatch; diff --git a/src/Interpreters/InterpreterAlterQuery.cpp b/src/Interpreters/InterpreterAlterQuery.cpp index e0b17213869..d2d7e36147a 100644 --- a/src/Interpreters/InterpreterAlterQuery.cpp +++ b/src/Interpreters/InterpreterAlterQuery.cpp @@ -70,7 +70,7 @@ BlockIO InterpreterAlterQuery::execute() { return executeToDatabase(alter); } - else if (alter.alter_object == ASTAlterQuery::AlterObjectType::TABLE) + if (alter.alter_object == ASTAlterQuery::AlterObjectType::TABLE) { return executeToTable(alter); } diff --git a/src/Interpreters/InterpreterCheckQuery.cpp b/src/Interpreters/InterpreterCheckQuery.cpp index 72a099fb455..eee8c5a3a17 100644 --- a/src/Interpreters/InterpreterCheckQuery.cpp +++ b/src/Interpreters/InterpreterCheckQuery.cpp @@ -262,10 +262,8 @@ private: LOG_DEBUG(log, "Checking '{}' database", database_name); return current_database; } - else - { - LOG_DEBUG(log, "Skipping database '{}' because it was dropped", database_name); - } + + LOG_DEBUG(log, "Skipping database '{}' because it was dropped", database_name); } return {}; } @@ -345,7 +343,7 @@ public: if (result_value == 0) return; - auto columns = chunk.getColumns(); + const auto & columns = chunk.getColumns(); if ((columns.size() != 3 && columns.size() != 5) || column_position_to_check >= columns.size()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Wrong number of columns: {}, position {}", columns.size(), column_position_to_check); diff --git a/src/Interpreters/InterpreterCreateIndexQuery.cpp b/src/Interpreters/InterpreterCreateIndexQuery.cpp index cb474ecdc3c..82d0318d3b6 100644 --- a/src/Interpreters/InterpreterCreateIndexQuery.cpp +++ b/src/Interpreters/InterpreterCreateIndexQuery.cpp @@ -53,11 +53,9 @@ BlockIO InterpreterCreateIndexQuery::execute() throw Exception(ErrorCodes::INCORRECT_QUERY, "CREATE INDEX without TYPE is forbidden." " SET allow_create_index_without_type=1 to ignore this statements"); } - else - { - // Nothing to do - return {}; - } + + // Nothing to do + return {}; } AccessRightsElements required_access; diff --git a/src/Interpreters/InterpreterCreateQuery.cpp b/src/Interpreters/InterpreterCreateQuery.cpp index 641c69ef5f2..e1784842cb9 100644 --- a/src/Interpreters/InterpreterCreateQuery.cpp +++ b/src/Interpreters/InterpreterCreateQuery.cpp @@ -188,8 +188,7 @@ BlockIO InterpreterCreateQuery::createDatabase(ASTCreateQuery & create) { if (create.if_not_exists) return {}; - else - throw Exception(ErrorCodes::DATABASE_ALREADY_EXISTS, "Database {} already exists.", database_name); + throw Exception(ErrorCodes::DATABASE_ALREADY_EXISTS, "Database {} already exists.", database_name); } auto db_num_limit = getContext()->getGlobalContext()->getServerSettings().max_database_num_to_throw; @@ -268,7 +267,7 @@ BlockIO InterpreterCreateQuery::createDatabase(ASTCreateQuery & create) if (create.attach && create.uuid == UUIDHelpers::Nil) throw Exception(ErrorCodes::INCORRECT_QUERY, "UUID must be specified for ATTACH. " "If you want to attach existing database, use just ATTACH DATABASE {};", create.getDatabase()); - else if (create.uuid == UUIDHelpers::Nil) + if (create.uuid == UUIDHelpers::Nil) create.uuid = UUIDHelpers::generateV4(); metadata_path = metadata_path / "store" / DatabaseCatalog::getPathForUUID(create.uuid); @@ -1369,17 +1368,23 @@ void InterpreterCreateQuery::assertOrSetUUID(ASTCreateQuery & create, const Data throw Exception(ErrorCodes::BAD_ARGUMENTS, "It's not allowed to explicitly specify UUIDs for tables in Replicated databases, " "see database_replicated_allow_explicit_uuid"); } - else if (getContext()->getSettingsRef()[Setting::database_replicated_allow_explicit_uuid] == 1) + if (getContext()->getSettingsRef()[Setting::database_replicated_allow_explicit_uuid] == 1) { - LOG_WARNING(&Poco::Logger::get("InterpreterCreateQuery"), "It's not recommended to explicitly specify UUIDs for tables in Replicated databases"); + LOG_WARNING( + &Poco::Logger::get("InterpreterCreateQuery"), + "It's not recommended to explicitly specify UUIDs for tables in Replicated databases"); } else if (getContext()->getSettingsRef()[Setting::database_replicated_allow_explicit_uuid] == 2) { UUID old_uuid = create.uuid; create.uuid = UUIDHelpers::Nil; create.generateRandomUUIDs(); - LOG_WARNING(&Poco::Logger::get("InterpreterCreateQuery"), "Replaced a user-provided UUID ({}) with a random one ({}) " - "to make sure it's unique", old_uuid, create.uuid); + LOG_WARNING( + &Poco::Logger::get("InterpreterCreateQuery"), + "Replaced a user-provided UUID ({}) with a random one ({}) " + "to make sure it's unique", + old_uuid, + create.uuid); } } @@ -1745,7 +1750,7 @@ bool InterpreterCreateQuery::doCreateTable(ASTCreateQuery & create, /// TODO Check structure of table if (create.if_not_exists) return false; - else if (create.replace_view) + if (create.replace_view) { /// when executing CREATE OR REPLACE VIEW, drop current existing view auto drop_ast = std::make_shared(); @@ -1763,11 +1768,16 @@ bool InterpreterCreateQuery::doCreateTable(ASTCreateQuery & create, else { if (database->getTable(create.getTable(), getContext())->isDictionary()) - throw Exception(ErrorCodes::DICTIONARY_ALREADY_EXISTS, - "Dictionary {}.{} already exists", backQuoteIfNeed(create.getDatabase()), backQuoteIfNeed(create.getTable())); - else - throw Exception(ErrorCodes::TABLE_ALREADY_EXISTS, - "Table {}.{} already exists", backQuoteIfNeed(create.getDatabase()), backQuoteIfNeed(create.getTable())); + throw Exception( + ErrorCodes::DICTIONARY_ALREADY_EXISTS, + "Dictionary {}.{} already exists", + backQuoteIfNeed(create.getDatabase()), + backQuoteIfNeed(create.getTable())); + throw Exception( + ErrorCodes::TABLE_ALREADY_EXISTS, + "Table {}.{} already exists", + backQuoteIfNeed(create.getDatabase()), + backQuoteIfNeed(create.getTable())); } } else if (!create.attach) @@ -2223,8 +2233,7 @@ BlockIO InterpreterCreateQuery::execute() /// CREATE|ATTACH DATABASE if (is_create_database) return createDatabase(create); - else - return createTable(create); + return createTable(create); } diff --git a/src/Interpreters/InterpreterDeleteQuery.cpp b/src/Interpreters/InterpreterDeleteQuery.cpp index c5e44bddd51..832a240e95e 100644 --- a/src/Interpreters/InterpreterDeleteQuery.cpp +++ b/src/Interpreters/InterpreterDeleteQuery.cpp @@ -95,7 +95,7 @@ BlockIO InterpreterDeleteQuery::execute() table->mutate(mutation_commands, getContext()); return {}; } - else if (table->supportsLightweightDelete()) + if (table->supportsLightweightDelete()) { if (!getContext()->getSettingsRef()[Setting::enable_lightweight_delete]) throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, @@ -115,12 +115,10 @@ BlockIO InterpreterDeleteQuery::execute() } /// Build "ALTER ... UPDATE _row_exists = 0 WHERE predicate" query - String alter_query = - "ALTER TABLE " + table->getStorageID().getFullTableName() - + (delete_query.cluster.empty() ? "" : " ON CLUSTER " + backQuoteIfNeed(delete_query.cluster)) - + " UPDATE `_row_exists` = 0" - + (delete_query.partition ? " IN PARTITION " + serializeAST(*delete_query.partition) : "") - + " WHERE " + serializeAST(*delete_query.predicate); + String alter_query = "ALTER TABLE " + table->getStorageID().getFullTableName() + + (delete_query.cluster.empty() ? "" : " ON CLUSTER " + backQuoteIfNeed(delete_query.cluster)) + " UPDATE `_row_exists` = 0" + + (delete_query.partition ? " IN PARTITION " + serializeAST(*delete_query.partition) : "") + " WHERE " + + serializeAST(*delete_query.predicate); ParserAlterQuery parser; ASTPtr alter_ast = parseQuery( @@ -137,12 +135,8 @@ BlockIO InterpreterDeleteQuery::execute() InterpreterAlterQuery alter_interpreter(alter_ast, context); return alter_interpreter.execute(); } - else - { - throw Exception(ErrorCodes::BAD_ARGUMENTS, - "DELETE query is not supported for table {}", - table->getStorageID().getFullTableName()); - } + + throw Exception(ErrorCodes::BAD_ARGUMENTS, "DELETE query is not supported for table {}", table->getStorageID().getFullTableName()); } void registerInterpreterDeleteQuery(InterpreterFactory & factory) diff --git a/src/Interpreters/InterpreterDropQuery.cpp b/src/Interpreters/InterpreterDropQuery.cpp index 1f4aa9fa1b7..12e40d00b13 100644 --- a/src/Interpreters/InterpreterDropQuery.cpp +++ b/src/Interpreters/InterpreterDropQuery.cpp @@ -93,16 +93,15 @@ BlockIO InterpreterDropQuery::executeSingleDropQuery(const ASTPtr & drop_query_p if (drop.table) return executeToTable(drop); - else if (drop.database && !drop.cluster.empty() && !maybeRemoveOnCluster(current_query_ptr, getContext())) + if (drop.database && !drop.cluster.empty() && !maybeRemoveOnCluster(current_query_ptr, getContext())) { DDLQueryOnClusterParams params; params.access_to_check = getRequiredAccessForDDLOnCluster(); return executeDDLQueryOnCluster(current_query_ptr, getContext(), params); } - else if (drop.database) + if (drop.database) return executeToDatabase(drop); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Nothing to drop, both names are empty"); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Nothing to drop, both names are empty"); } void InterpreterDropQuery::waitForTableToBeActuallyDroppedOrDetached(const ASTDropQuery & query, const DatabasePtr & db, const UUID & uuid_to_wait) @@ -134,8 +133,7 @@ BlockIO InterpreterDropQuery::executeToTableImpl(const ContextPtr & context_, AS { if (context_->tryResolveStorageID(table_id, Context::ResolveExternal)) return executeToTemporaryTable(table_id.getTableName(), query.kind); - else - query.setDatabase(table_id.database_name = context_->getCurrentDatabase()); + query.setDatabase(table_id.database_name = context_->getCurrentDatabase()); } if (query.temporary) @@ -330,29 +328,27 @@ BlockIO InterpreterDropQuery::executeToTemporaryTable(const String & table_name, { if (kind == ASTDropQuery::Kind::Detach) throw Exception(ErrorCodes::SYNTAX_ERROR, "Unable to detach temporary table."); - else + + auto context_handle = getContext()->hasSessionContext() ? getContext()->getSessionContext() : getContext(); + auto resolved_id = context_handle->tryResolveStorageID(StorageID("", table_name), Context::ResolveExternal); + if (resolved_id) { - auto context_handle = getContext()->hasSessionContext() ? getContext()->getSessionContext() : getContext(); - auto resolved_id = context_handle->tryResolveStorageID(StorageID("", table_name), Context::ResolveExternal); - if (resolved_id) + StoragePtr table = DatabaseCatalog::instance().getTable(resolved_id, getContext()); + if (kind == ASTDropQuery::Kind::Truncate) { - StoragePtr table = DatabaseCatalog::instance().getTable(resolved_id, getContext()); - if (kind == ASTDropQuery::Kind::Truncate) - { - auto table_lock - = table->lockExclusively(getContext()->getCurrentQueryId(), getContext()->getSettingsRef()[Setting::lock_acquire_timeout]); - /// Drop table data, don't touch metadata - auto metadata_snapshot = table->getInMemoryMetadataPtr(); - table->truncate(current_query_ptr, metadata_snapshot, getContext(), table_lock); - } - else if (kind == ASTDropQuery::Kind::Drop) - { - context_handle->removeExternalTable(table_name); - } - else if (kind == ASTDropQuery::Kind::Detach) - { - table->is_detached = true; - } + auto table_lock + = table->lockExclusively(getContext()->getCurrentQueryId(), getContext()->getSettingsRef()[Setting::lock_acquire_timeout]); + /// Drop table data, don't touch metadata + auto metadata_snapshot = table->getInMemoryMetadataPtr(); + table->truncate(current_query_ptr, metadata_snapshot, getContext(), table_lock); + } + else if (kind == ASTDropQuery::Kind::Drop) + { + context_handle->removeExternalTable(table_name); + } + else if (kind == ASTDropQuery::Kind::Detach) + { + table->is_detached = true; } } diff --git a/src/Interpreters/InterpreterExplainQuery.cpp b/src/Interpreters/InterpreterExplainQuery.cpp index fdd138117d8..2841d042cdc 100644 --- a/src/Interpreters/InterpreterExplainQuery.cpp +++ b/src/Interpreters/InterpreterExplainQuery.cpp @@ -119,16 +119,14 @@ Block InterpreterExplainQuery::getSampleBlock(const ASTExplainQuery::ExplainKind {cols[4].type->createColumn(), cols[4].type, cols[4].name}, }); } - else - { - Block res; - ColumnWithTypeAndName col; - col.name = "explain"; - col.type = std::make_shared(); - col.column = col.type->createColumn(); - res.insert(col); - return res; - } + + Block res; + ColumnWithTypeAndName col; + col.name = "explain"; + col.type = std::make_shared(); + col.column = col.type->createColumn(); + res.insert(col); + return res; } /// Split str by line feed and write as separate row to ColumnString. diff --git a/src/Interpreters/InterpreterExternalDDLQuery.cpp b/src/Interpreters/InterpreterExternalDDLQuery.cpp index e68ff18dbb6..f9104bda7f6 100644 --- a/src/Interpreters/InterpreterExternalDDLQuery.cpp +++ b/src/Interpreters/InterpreterExternalDDLQuery.cpp @@ -50,18 +50,18 @@ BlockIO InterpreterExternalDDLQuery::execute() return MySQLInterpreter::InterpreterMySQLDropQuery( external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]), getIdentifierName(arguments[1])).execute(); - else if (external_ddl_query.external_ddl->as()) + if (external_ddl_query.external_ddl->as()) return MySQLInterpreter::InterpreterMySQLRenameQuery( - external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]), - getIdentifierName(arguments[1])).execute(); - else if (external_ddl_query.external_ddl->as()) + external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]), getIdentifierName(arguments[1])) + .execute(); + if (external_ddl_query.external_ddl->as()) return MySQLInterpreter::InterpreterMySQLAlterQuery( - external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]), - getIdentifierName(arguments[1])).execute(); - else if (external_ddl_query.external_ddl->as()) + external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]), getIdentifierName(arguments[1])) + .execute(); + if (external_ddl_query.external_ddl->as()) return MySQLInterpreter::InterpreterMySQLCreateQuery( - external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]), - getIdentifierName(arguments[1])).execute(); + external_ddl_query.external_ddl, getContext(), getIdentifierName(arguments[0]), getIdentifierName(arguments[1])) + .execute(); #endif } diff --git a/src/Interpreters/InterpreterInsertQuery.cpp b/src/Interpreters/InterpreterInsertQuery.cpp index ef7d90d3ac1..d6058c55344 100644 --- a/src/Interpreters/InterpreterInsertQuery.cpp +++ b/src/Interpreters/InterpreterInsertQuery.cpp @@ -163,10 +163,9 @@ Block InterpreterInsertQuery::getSampleBlock( { if (auto * window_view = dynamic_cast(table.get())) return window_view->getInputHeader(); - else if (no_destination) + if (no_destination) return metadata_snapshot->getSampleBlockWithVirtuals(table->getVirtualsList()); - else - return metadata_snapshot->getSampleBlockNonMaterialized(); + return metadata_snapshot->getSampleBlockNonMaterialized(); } /// Form the block based on the column names from the query diff --git a/src/Interpreters/InterpreterRenameQuery.cpp b/src/Interpreters/InterpreterRenameQuery.cpp index ffa52b7ecf8..92d0cc310e8 100644 --- a/src/Interpreters/InterpreterRenameQuery.cpp +++ b/src/Interpreters/InterpreterRenameQuery.cpp @@ -78,8 +78,7 @@ BlockIO InterpreterRenameQuery::execute() if (rename.database) return executeToDatabase(rename, descriptions); - else - return executeToTables(rename, descriptions, table_guards); + return executeToTables(rename, descriptions, table_guards); } BlockIO InterpreterRenameQuery::executeToTables(const ASTRenameQuery & rename, const RenameDescriptions & descriptions, TableGuards & ddl_guards) @@ -129,52 +128,48 @@ BlockIO InterpreterRenameQuery::executeToTables(const ASTRenameQuery & rename, c ddl_guards[to]->releaseTableLock(); return database->tryEnqueueReplicatedDDL(query_ptr, getContext()); } + + StorageID from_table_id{elem.from_database_name, elem.from_table_name}; + StorageID to_table_id{elem.to_database_name, elem.to_table_name}; + std::vector from_ref_dependencies; + std::vector from_loading_dependencies; + std::vector to_ref_dependencies; + std::vector to_loading_dependencies; + + if (exchange_tables) + { + DatabaseCatalog::instance().checkTablesCanBeExchangedWithNoCyclicDependencies(from_table_id, to_table_id); + std::tie(from_ref_dependencies, from_loading_dependencies) = database_catalog.removeDependencies(from_table_id, false, false); + std::tie(to_ref_dependencies, to_loading_dependencies) = database_catalog.removeDependencies(to_table_id, false, false); + } else { - StorageID from_table_id{elem.from_database_name, elem.from_table_name}; - StorageID to_table_id{elem.to_database_name, elem.to_table_name}; - std::vector from_ref_dependencies; - std::vector from_loading_dependencies; - std::vector to_ref_dependencies; - std::vector to_loading_dependencies; + DatabaseCatalog::instance().checkTableCanBeRenamedWithNoCyclicDependencies(from_table_id, to_table_id); + bool check_ref_deps = getContext()->getSettingsRef()[Setting::check_referential_table_dependencies]; + bool check_loading_deps = !check_ref_deps && getContext()->getSettingsRef()[Setting::check_table_dependencies]; + std::tie(from_ref_dependencies, from_loading_dependencies) = database_catalog.removeDependencies(from_table_id, check_ref_deps, check_loading_deps); + } + try + { + database->renameTable( + getContext(), + elem.from_table_name, + *database_catalog.getDatabase(elem.to_database_name), + elem.to_table_name, + exchange_tables, + rename.dictionary); - if (exchange_tables) - { - DatabaseCatalog::instance().checkTablesCanBeExchangedWithNoCyclicDependencies(from_table_id, to_table_id); - std::tie(from_ref_dependencies, from_loading_dependencies) = database_catalog.removeDependencies(from_table_id, false, false); - std::tie(to_ref_dependencies, to_loading_dependencies) = database_catalog.removeDependencies(to_table_id, false, false); - } - else - { - DatabaseCatalog::instance().checkTableCanBeRenamedWithNoCyclicDependencies(from_table_id, to_table_id); - bool check_ref_deps = getContext()->getSettingsRef()[Setting::check_referential_table_dependencies]; - bool check_loading_deps = !check_ref_deps && getContext()->getSettingsRef()[Setting::check_table_dependencies]; - std::tie(from_ref_dependencies, from_loading_dependencies) = database_catalog.removeDependencies(from_table_id, check_ref_deps, check_loading_deps); - } - - try - { - database->renameTable( - getContext(), - elem.from_table_name, - *database_catalog.getDatabase(elem.to_database_name), - elem.to_table_name, - exchange_tables, - rename.dictionary); - - DatabaseCatalog::instance().addDependencies(to_table_id, from_ref_dependencies, from_loading_dependencies); - if (!to_ref_dependencies.empty() || !to_loading_dependencies.empty()) - DatabaseCatalog::instance().addDependencies(from_table_id, to_ref_dependencies, to_loading_dependencies); - - } - catch (...) - { - /// Restore dependencies if RENAME fails - DatabaseCatalog::instance().addDependencies(from_table_id, from_ref_dependencies, from_loading_dependencies); - if (!to_ref_dependencies.empty() || !to_loading_dependencies.empty()) - DatabaseCatalog::instance().addDependencies(to_table_id, to_ref_dependencies, to_loading_dependencies); - throw; - } + DatabaseCatalog::instance().addDependencies(to_table_id, from_ref_dependencies, from_loading_dependencies); + if (!to_ref_dependencies.empty() || !to_loading_dependencies.empty()) + DatabaseCatalog::instance().addDependencies(from_table_id, to_ref_dependencies, to_loading_dependencies); + } + catch (...) + { + /// Restore dependencies if RENAME fails + DatabaseCatalog::instance().addDependencies(from_table_id, from_ref_dependencies, from_loading_dependencies); + if (!to_ref_dependencies.empty() || !to_loading_dependencies.empty()) + DatabaseCatalog::instance().addDependencies(to_table_id, to_ref_dependencies, to_loading_dependencies); + throw; } } diff --git a/src/Interpreters/InterpreterSelectQuery.cpp b/src/Interpreters/InterpreterSelectQuery.cpp index de86a8b91ad..30260ebbea9 100644 --- a/src/Interpreters/InterpreterSelectQuery.cpp +++ b/src/Interpreters/InterpreterSelectQuery.cpp @@ -816,24 +816,22 @@ InterpreterSelectQuery::InterpreterSelectQuery( ErrorCodes::SAMPLING_NOT_SUPPORTED, "Storage {} doesn't support sampling", storage->getStorageID().getNameForLogs()); - else - throw Exception(ErrorCodes::SAMPLING_NOT_SUPPORTED, "Illegal SAMPLE: sampling is only allowed with the table engines that support it"); + throw Exception( + ErrorCodes::SAMPLING_NOT_SUPPORTED, "Illegal SAMPLE: sampling is only allowed with the table engines that support it"); } if (query.final() && (input_pipe || !storage || !storage->supportsFinal())) { if (!input_pipe && storage) throw Exception(ErrorCodes::ILLEGAL_FINAL, "Storage {} doesn't support FINAL", storage->getName()); - else - throw Exception(ErrorCodes::ILLEGAL_FINAL, "Illegal FINAL"); + throw Exception(ErrorCodes::ILLEGAL_FINAL, "Illegal FINAL"); } if (query.prewhere() && (input_pipe || !storage || !storage->supportsPrewhere())) { if (!input_pipe && storage) throw Exception(ErrorCodes::ILLEGAL_PREWHERE, "Storage {} doesn't support PREWHERE", storage->getName()); - else - throw Exception(ErrorCodes::ILLEGAL_PREWHERE, "Illegal PREWHERE"); + throw Exception(ErrorCodes::ILLEGAL_PREWHERE, "Illegal PREWHERE"); } /// Save the new temporary tables in the query context @@ -1075,7 +1073,7 @@ bool InterpreterSelectQuery::adjustParallelReplicasAfterAnalysis() LOG_DEBUG(log, "Disabling parallel replicas because there aren't enough rows to read"); return true; } - else if (number_of_replicas_to_use < settings[Setting::max_parallel_replicas]) + if (number_of_replicas_to_use < settings[Setting::max_parallel_replicas]) { context->setSetting("max_parallel_replicas", number_of_replicas_to_use); LOG_DEBUG(log, "Reducing the number of replicas to use to {}", number_of_replicas_to_use); @@ -2442,29 +2440,27 @@ std::optional InterpreterSelectQuery::getTrivialCount(UInt64 allow_exper query_info.optimize_trivial_count = optimize_trivial_count; return storage->totalRows(settings); } - else + + // It's possible to optimize count() given only partition predicates + ActionsDAG::NodeRawConstPtrs filter_nodes; + if (analysis_result.hasPrewhere()) { - // It's possible to optimize count() given only partition predicates - ActionsDAG::NodeRawConstPtrs filter_nodes; - if (analysis_result.hasPrewhere()) - { - auto & prewhere_info = analysis_result.prewhere_info; - filter_nodes.push_back(&prewhere_info->prewhere_actions.findInOutputs(prewhere_info->prewhere_column_name)); + auto & prewhere_info = analysis_result.prewhere_info; + filter_nodes.push_back(&prewhere_info->prewhere_actions.findInOutputs(prewhere_info->prewhere_column_name)); - if (prewhere_info->row_level_filter) - filter_nodes.push_back(&prewhere_info->row_level_filter->findInOutputs(prewhere_info->row_level_column_name)); - } - if (analysis_result.hasWhere()) - { - filter_nodes.push_back(&analysis_result.before_where->dag.findInOutputs(analysis_result.where_column_name)); - } - - auto filter_actions_dag = ActionsDAG::buildFilterActionsDAG(filter_nodes); - if (!filter_actions_dag) - return {}; - - return storage->totalRowsByPartitionPredicate(*filter_actions_dag, context); + if (prewhere_info->row_level_filter) + filter_nodes.push_back(&prewhere_info->row_level_filter->findInOutputs(prewhere_info->row_level_column_name)); } + if (analysis_result.hasWhere()) + { + filter_nodes.push_back(&analysis_result.before_where->dag.findInOutputs(analysis_result.where_column_name)); + } + + auto filter_actions_dag = ActionsDAG::buildFilterActionsDAG(filter_nodes); + if (!filter_actions_dag) + return {}; + + return storage->totalRowsByPartitionPredicate(*filter_actions_dag, context); } /** Optimization - if not specified DISTINCT, WHERE, GROUP, HAVING, ORDER, JOIN, LIMIT BY, WITH TIES @@ -2963,15 +2959,15 @@ static bool windowDescriptionComparator(const WindowDescription * _left, const W { if (left[i].column_name < right[i].column_name) return true; - else if (left[i].column_name > right[i].column_name) + if (left[i].column_name > right[i].column_name) return false; - else if (left[i].direction < right[i].direction) + if (left[i].direction < right[i].direction) return true; - else if (left[i].direction > right[i].direction) + if (left[i].direction > right[i].direction) return false; - else if (left[i].nulls_direction < right[i].nulls_direction) + if (left[i].nulls_direction < right[i].nulls_direction) return true; - else if (left[i].nulls_direction > right[i].nulls_direction) + if (left[i].nulls_direction > right[i].nulls_direction) return false; assert(left[i] == right[i]); diff --git a/src/Interpreters/InterpreterSelectWithUnionQuery.cpp b/src/Interpreters/InterpreterSelectWithUnionQuery.cpp index 8f0a47df5aa..eec0e1f27c9 100644 --- a/src/Interpreters/InterpreterSelectWithUnionQuery.cpp +++ b/src/Interpreters/InterpreterSelectWithUnionQuery.cpp @@ -252,10 +252,9 @@ Block InterpreterSelectWithUnionQuery::getCurrentChildResultHeader(const ASTPtr if (ast_ptr_->as()) return InterpreterSelectWithUnionQuery(ast_ptr_, context, options.copy().analyze().noModify(), required_result_column_names) .getSampleBlock(); - else if (ast_ptr_->as()) + if (ast_ptr_->as()) return InterpreterSelectQuery(ast_ptr_, context, options.copy().analyze().noModify()).getSampleBlock(); - else - return InterpreterSelectIntersectExceptQuery(ast_ptr_, context, options.copy().analyze().noModify()).getSampleBlock(); + return InterpreterSelectIntersectExceptQuery(ast_ptr_, context, options.copy().analyze().noModify()).getSampleBlock(); } std::unique_ptr @@ -263,10 +262,9 @@ InterpreterSelectWithUnionQuery::buildCurrentChildInterpreter(const ASTPtr & ast { if (ast_ptr_->as()) return std::make_unique(ast_ptr_, context, options, current_required_result_column_names); - else if (ast_ptr_->as()) + if (ast_ptr_->as()) return std::make_unique(ast_ptr_, context, options, current_required_result_column_names); - else - return std::make_unique(ast_ptr_, context, options); + return std::make_unique(ast_ptr_, context, options); } InterpreterSelectWithUnionQuery::~InterpreterSelectWithUnionQuery() = default; diff --git a/src/Interpreters/InterpreterShowTablesQuery.cpp b/src/Interpreters/InterpreterShowTablesQuery.cpp index 78580f2ec02..75dae86abb7 100644 --- a/src/Interpreters/InterpreterShowTablesQuery.cpp +++ b/src/Interpreters/InterpreterShowTablesQuery.cpp @@ -81,7 +81,7 @@ String InterpreterShowTablesQuery::getRewrittenQuery() return rewritten_query.str(); } - else if (query.cluster) + if (query.cluster) { WriteBufferFromOwnString rewritten_query; rewritten_query << "SELECT * FROM system.clusters"; diff --git a/src/Interpreters/InterpreterSystemQuery.cpp b/src/Interpreters/InterpreterSystemQuery.cpp index cb731333aed..6ff608c1841 100644 --- a/src/Interpreters/InterpreterSystemQuery.cpp +++ b/src/Interpreters/InterpreterSystemQuery.cpp @@ -163,26 +163,25 @@ AccessType getRequiredAccessType(StorageActionBlockType action_type) { if (action_type == ActionLocks::PartsMerge) return AccessType::SYSTEM_MERGES; - else if (action_type == ActionLocks::PartsFetch) + if (action_type == ActionLocks::PartsFetch) return AccessType::SYSTEM_FETCHES; - else if (action_type == ActionLocks::PartsSend) + if (action_type == ActionLocks::PartsSend) return AccessType::SYSTEM_REPLICATED_SENDS; - else if (action_type == ActionLocks::ReplicationQueue) + if (action_type == ActionLocks::ReplicationQueue) return AccessType::SYSTEM_REPLICATION_QUEUES; - else if (action_type == ActionLocks::DistributedSend) + if (action_type == ActionLocks::DistributedSend) return AccessType::SYSTEM_DISTRIBUTED_SENDS; - else if (action_type == ActionLocks::PartsTTLMerge) + if (action_type == ActionLocks::PartsTTLMerge) return AccessType::SYSTEM_TTL_MERGES; - else if (action_type == ActionLocks::PartsMove) + if (action_type == ActionLocks::PartsMove) return AccessType::SYSTEM_MOVES; - else if (action_type == ActionLocks::PullReplicationLog) + if (action_type == ActionLocks::PullReplicationLog) return AccessType::SYSTEM_PULLING_REPLICATION_LOG; - else if (action_type == ActionLocks::Cleanup) + if (action_type == ActionLocks::Cleanup) return AccessType::SYSTEM_CLEANUP; - else if (action_type == ActionLocks::ViewRefresh) + if (action_type == ActionLocks::ViewRefresh) return AccessType::SYSTEM_VIEWS; - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown action type: {}", std::to_string(action_type)); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown action type: {}", std::to_string(action_type)); } constexpr std::string_view table_is_not_replicated = "Table {} is not replicated"; diff --git a/src/Interpreters/InterpreterTransactionControlQuery.cpp b/src/Interpreters/InterpreterTransactionControlQuery.cpp index 217c8b9ff02..c114e6b7d14 100644 --- a/src/Interpreters/InterpreterTransactionControlQuery.cpp +++ b/src/Interpreters/InterpreterTransactionControlQuery.cpp @@ -59,8 +59,7 @@ BlockIO InterpreterTransactionControlQuery::executeCommit(ContextMutablePtr sess { if (session_context->getClientInfo().interface == ClientInfo::Interface::MYSQL) return {}; - else - throw Exception(ErrorCodes::INVALID_TRANSACTION, "There is no current transaction"); + throw Exception(ErrorCodes::INVALID_TRANSACTION, "There is no current transaction"); } if (txn->getState() != MergeTreeTransaction::RUNNING) throw Exception(ErrorCodes::INVALID_TRANSACTION, "Transaction is not in RUNNING state"); @@ -123,8 +122,7 @@ BlockIO InterpreterTransactionControlQuery::executeRollback(ContextMutablePtr se { if (session_context->getClientInfo().interface == ClientInfo::Interface::MYSQL) return {}; - else - throw Exception(ErrorCodes::INVALID_TRANSACTION, "There is no current transaction"); + throw Exception(ErrorCodes::INVALID_TRANSACTION, "There is no current transaction"); } if (txn->getState() == MergeTreeTransaction::COMMITTED) throw Exception(ErrorCodes::LOGICAL_ERROR, "Transaction is in COMMITTED state"); diff --git a/src/Interpreters/InterpreterUndropQuery.cpp b/src/Interpreters/InterpreterUndropQuery.cpp index 8f935e951ef..1a1a7558bc8 100644 --- a/src/Interpreters/InterpreterUndropQuery.cpp +++ b/src/Interpreters/InterpreterUndropQuery.cpp @@ -38,8 +38,7 @@ BlockIO InterpreterUndropQuery::execute() if (undrop.table) return executeToTable(undrop); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Nothing to undrop, both names are empty"); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Nothing to undrop, both names are empty"); } BlockIO InterpreterUndropQuery::executeToTable(ASTUndropQuery & query) diff --git a/src/Interpreters/InterpreterWatchQuery.cpp b/src/Interpreters/InterpreterWatchQuery.cpp index dae4b41f889..28c97797ee5 100644 --- a/src/Interpreters/InterpreterWatchQuery.cpp +++ b/src/Interpreters/InterpreterWatchQuery.cpp @@ -80,7 +80,7 @@ QueryPipelineBuilder InterpreterWatchQuery::buildQueryPipeline() if (storage_name == "LiveView" && !getContext()->getSettingsRef()[Setting::allow_experimental_live_view]) throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Experimental LIVE VIEW feature is not enabled (the setting 'allow_experimental_live_view')"); - else if (storage_name == "WindowView" && !getContext()->getSettingsRef()[Setting::allow_experimental_window_view]) + if (storage_name == "WindowView" && !getContext()->getSettingsRef()[Setting::allow_experimental_window_view]) throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Experimental WINDOW VIEW feature is not enabled (the setting 'allow_experimental_window_view')"); diff --git a/src/Interpreters/JIT/CHJIT.cpp b/src/Interpreters/JIT/CHJIT.cpp index 21c773ee1d7..8e4f73a1bea 100644 --- a/src/Interpreters/JIT/CHJIT.cpp +++ b/src/Interpreters/JIT/CHJIT.cpp @@ -217,10 +217,8 @@ private: return static_cast(result); } - else - { - return nullptr; - } + + return nullptr; } void allocateNextPageBlock(size_t size) @@ -287,8 +285,7 @@ public: { if (is_read_only) return reinterpret_cast(ro_page_arena.allocate(size, alignment)); - else - return reinterpret_cast(rw_page_arena.allocate(size, alignment)); + return reinterpret_cast(rw_page_arena.allocate(size, alignment)); } bool finalizeMemory(std::string *) override diff --git a/src/Interpreters/JoinUtils.cpp b/src/Interpreters/JoinUtils.cpp index 180a45d4295..d48ae16d3cd 100644 --- a/src/Interpreters/JoinUtils.cpp +++ b/src/Interpreters/JoinUtils.cpp @@ -157,7 +157,7 @@ static ColumnPtr tryConvertColumnToNullable(ColumnPtr col) { return col; } - else if (col_lc.nestedCanBeInsideNullable()) + if (col_lc.nestedCanBeInsideNullable()) { return col_lc.cloneNullable(); } @@ -169,7 +169,7 @@ static ColumnPtr tryConvertColumnToNullable(ColumnPtr col) { return makeNullable(col); } - else if (nested->lowCardinality()) + if (nested->lowCardinality()) { ColumnPtr nested_nullable = tryConvertColumnToNullable(nested); if (nested_nullable) @@ -510,8 +510,7 @@ JoinMask getColumnAsMask(const Block & block, const String & column_name) res->getData()[i] = !null_map.getData()[i] && nest_col.getData()[i]; return JoinMask(std::move(res)); } - else - return JoinMask(std::move(join_condition_col)); + return JoinMask(std::move(join_condition_col)); } diff --git a/src/Interpreters/MergeJoin.cpp b/src/Interpreters/MergeJoin.cpp index b374175d466..4c6f565e266 100644 --- a/src/Interpreters/MergeJoin.cpp +++ b/src/Interpreters/MergeJoin.cpp @@ -37,8 +37,7 @@ String deriveTempName(const String & name, JoinTableSide block_side) { if (block_side == JoinTableSide::Left) return "--pmj_cond_left_" + name; - else - return "--pmj_cond_right_" + name; + return "--pmj_cond_right_" + name; } /* @@ -263,9 +262,9 @@ public: { if (has_left_nullable && has_right_nullable) return getNextEqualRangeImpl(rhs); - else if (has_left_nullable) + if (has_left_nullable) return getNextEqualRangeImpl(rhs); - else if (has_right_nullable) + if (has_right_nullable) return getNextEqualRangeImpl(rhs); return getNextEqualRangeImpl(rhs); } diff --git a/src/Interpreters/MergeTreeTransaction.cpp b/src/Interpreters/MergeTreeTransaction.cpp index b389b6cbb4b..82a30dfa6df 100644 --- a/src/Interpreters/MergeTreeTransaction.cpp +++ b/src/Interpreters/MergeTreeTransaction.cpp @@ -65,7 +65,7 @@ void MergeTreeTransaction::checkIsNotCancelled() const CSN c = csn.load(); if (c == Tx::RolledBackCSN) throw Exception(ErrorCodes::INVALID_TRANSACTION, "Transaction was cancelled"); - else if (c != Tx::UnknownCSN) + if (c != Tx::UnknownCSN) throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected CSN state: {}", c); } diff --git a/src/Interpreters/MutationsInterpreter.cpp b/src/Interpreters/MutationsInterpreter.cpp index b0d9e4de0d7..676133e8328 100644 --- a/src/Interpreters/MutationsInterpreter.cpp +++ b/src/Interpreters/MutationsInterpreter.cpp @@ -227,7 +227,7 @@ bool isStorageTouchedByMutations( if (!block.rows()) return false; - else if (block.rows() != 1) + if (block.rows() != 1) throw Exception(ErrorCodes::LOGICAL_ERROR, "count() expression returned {} rows, not 1", block.rows()); Block tmp_block; @@ -265,8 +265,7 @@ ASTPtr getPartitionAndPredicateExpressionForMutationCommand( if (command.predicate && command.partition) return makeASTFunction("and", command.predicate->clone(), std::move(partition_predicate_as_ast_func)); - else - return command.predicate ? command.predicate->clone() : partition_predicate_as_ast_func; + return command.predicate ? command.predicate->clone() : partition_predicate_as_ast_func; } diff --git a/src/Interpreters/MySQL/InterpretersMySQLDDLQuery.cpp b/src/Interpreters/MySQL/InterpretersMySQLDDLQuery.cpp index 7296bdaf383..c7fd800cacc 100644 --- a/src/Interpreters/MySQL/InterpretersMySQLDDLQuery.cpp +++ b/src/Interpreters/MySQL/InterpretersMySQLDDLQuery.cpp @@ -55,12 +55,10 @@ static inline String resolveDatabase( /// USE replica_mysql_database; CREATE TABLE replica_mysql_database.table_name; return replica_clickhouse_database; } - else - { - /// USE other_database_name; CREATE TABLE other_database_name.table_name; - /// USE replica_mysql_database; CREATE TABLE other_database_name.table_name; - return ""; - } + + /// USE other_database_name; CREATE TABLE other_database_name.table_name; + /// USE replica_mysql_database; CREATE TABLE other_database_name.table_name; + return ""; } /// When USE other_database_name; CREATE TABLE table_name; diff --git a/src/Interpreters/OptimizeDateOrDateTimeConverterWithPreimageVisitor.cpp b/src/Interpreters/OptimizeDateOrDateTimeConverterWithPreimageVisitor.cpp index b2419018e18..51df8ad10ac 100644 --- a/src/Interpreters/OptimizeDateOrDateTimeConverterWithPreimageVisitor.cpp +++ b/src/Interpreters/OptimizeDateOrDateTimeConverterWithPreimageVisitor.cpp @@ -65,45 +65,31 @@ ASTPtr generateOptimizedDateFilterAST(const String & comparator, const NameAndTy ) ); } - else if (comparator == "notEquals") + if (comparator == "notEquals") { - return makeASTFunction("or", - makeASTFunction("less", - std::make_shared(column_name), - std::make_shared(start_date_or_date_time) - ), - makeASTFunction("greaterOrEquals", - std::make_shared(column_name), - std::make_shared(end_date_or_date_time) - ) - ); + return makeASTFunction( + "or", + makeASTFunction("less", std::make_shared(column_name), std::make_shared(start_date_or_date_time)), + makeASTFunction( + "greaterOrEquals", std::make_shared(column_name), std::make_shared(end_date_or_date_time))); } - else if (comparator == "greater") + if (comparator == "greater") { - return makeASTFunction("greaterOrEquals", - std::make_shared(column_name), - std::make_shared(end_date_or_date_time) - ); + return makeASTFunction( + "greaterOrEquals", std::make_shared(column_name), std::make_shared(end_date_or_date_time)); } - else if (comparator == "lessOrEquals") + if (comparator == "lessOrEquals") { - return makeASTFunction("less", - std::make_shared(column_name), - std::make_shared(end_date_or_date_time) - ); + return makeASTFunction("less", std::make_shared(column_name), std::make_shared(end_date_or_date_time)); } - else if (comparator == "less" || comparator == "greaterOrEquals") + if (comparator == "less" || comparator == "greaterOrEquals") { - return makeASTFunction(comparator, - std::make_shared(column_name), - std::make_shared(start_date_or_date_time) - ); + return makeASTFunction( + comparator, std::make_shared(column_name), std::make_shared(start_date_or_date_time)); } - else [[unlikely]] - { - throw Exception(ErrorCodes::LOGICAL_ERROR, - "Expected equals, notEquals, less, lessOrEquals, greater, greaterOrEquals. Actual {}", - comparator); + [[unlikely]] { + throw Exception( + ErrorCodes::LOGICAL_ERROR, "Expected equals, notEquals, less, lessOrEquals, greater, greaterOrEquals. Actual {}", comparator); } } diff --git a/src/Interpreters/OptimizeIfChains.cpp b/src/Interpreters/OptimizeIfChains.cpp index 9a5f9bcb2e1..6678f27207c 100644 --- a/src/Interpreters/OptimizeIfChains.cpp +++ b/src/Interpreters/OptimizeIfChains.cpp @@ -83,15 +83,13 @@ ASTs OptimizeIfChainsVisitor::ifChain(const ASTPtr & child) cur.push_back(function_node->arguments->children[0]); return cur; } - else - { - ASTs end; - end.reserve(3); - end.push_back(function_node->arguments->children[2]); - end.push_back(function_node->arguments->children[1]); - end.push_back(function_node->arguments->children[0]); - return end; - } + + ASTs end; + end.reserve(3); + end.push_back(function_node->arguments->children[2]); + end.push_back(function_node->arguments->children[1]); + end.push_back(function_node->arguments->children[0]); + return end; } } diff --git a/src/Interpreters/ProcessList.cpp b/src/Interpreters/ProcessList.cpp index 402cbee3c7c..0860e94c45e 100644 --- a/src/Interpreters/ProcessList.cpp +++ b/src/Interpreters/ProcessList.cpp @@ -787,10 +787,9 @@ void ProcessList::decreaseQueryKindAmount(const IAST::QueryKind & query_kind) /// TODO: we could just rebuild the map, as we have saved all query_kind. if (found == query_kind_amounts.end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Wrong query kind amount: decrease before increase on '{}'", query_kind); - else if (found->second == 0) + if (found->second == 0) throw Exception(ErrorCodes::LOGICAL_ERROR, "Wrong query kind amount: decrease to negative on '{}', {}", query_kind, found->second); - else - found->second -= 1; + found->second -= 1; } ProcessList::QueryAmount ProcessList::getQueryKindAmount(const IAST::QueryKind & query_kind) const diff --git a/src/Interpreters/RewriteArrayExistsFunctionVisitor.cpp b/src/Interpreters/RewriteArrayExistsFunctionVisitor.cpp index 3de9138491b..22ce91d8c67 100644 --- a/src/Interpreters/RewriteArrayExistsFunctionVisitor.cpp +++ b/src/Interpreters/RewriteArrayExistsFunctionVisitor.cpp @@ -87,8 +87,7 @@ void RewriteArrayExistsFunctionMatcher::visit(const ASTFunction & func, ASTPtr & ast = std::move(new_func); return; } - else if ( - (filter_id = filter_arguments[1]->as()) && filter_arguments[0]->as() + if ((filter_id = filter_arguments[1]->as()) && filter_arguments[0]->as() && filter_id->full_name == id->full_name) { /// arrayExists(x -> elem = x, arr) -> has(arr, elem) diff --git a/src/Interpreters/RewriteSumFunctionWithSumAndCountVisitor.cpp b/src/Interpreters/RewriteSumFunctionWithSumAndCountVisitor.cpp index 8e60603cca9..b8a187c931c 100644 --- a/src/Interpreters/RewriteSumFunctionWithSumAndCountVisitor.cpp +++ b/src/Interpreters/RewriteSumFunctionWithSumAndCountVisitor.cpp @@ -101,11 +101,9 @@ void RewriteSumFunctionWithSumAndCountMatcher::visit(const ASTFunction & functio ); if (!new_ast) return; - else - { - new_ast->setAlias(ast->tryGetAlias()); - ast = new_ast; - } + + new_ast->setAlias(ast->tryGetAlias()); + ast = new_ast; } else if (column_id == 1) { @@ -120,11 +118,9 @@ void RewriteSumFunctionWithSumAndCountMatcher::visit(const ASTFunction & functio ); if (!new_ast) return; - else - { - new_ast->setAlias(ast->tryGetAlias()); - ast = new_ast; - } + + new_ast->setAlias(ast->tryGetAlias()); + ast = new_ast; } } diff --git a/src/Interpreters/RewriteUniqToCountVisitor.cpp b/src/Interpreters/RewriteUniqToCountVisitor.cpp index a2e3a790c27..4c2df0e3527 100644 --- a/src/Interpreters/RewriteUniqToCountVisitor.cpp +++ b/src/Interpreters/RewriteUniqToCountVisitor.cpp @@ -28,30 +28,27 @@ bool matchFnUniq(String name) bool expressionEquals(const ASTPtr & lhs, const ASTPtr & rhs, const Aliases & alias) { if (lhs->getTreeHash(/*ignore_aliases=*/ true) == rhs->getTreeHash(/*ignore_aliases=*/ true)) - { return true; - } - else + + auto * lhs_idf = lhs->as(); + auto * rhs_idf = rhs->as(); + if (lhs_idf && rhs_idf) { - auto * lhs_idf = lhs->as(); - auto * rhs_idf = rhs->as(); - if (lhs_idf && rhs_idf) - { - /// compound identifiers, such as: - if (lhs_idf->shortName() == rhs_idf->shortName()) - return true; + /// compound identifiers, such as: + if (lhs_idf->shortName() == rhs_idf->shortName()) + return true; - /// translate alias - if (alias.find(lhs_idf->shortName()) != alias.end()) - lhs_idf = alias.find(lhs_idf->shortName())->second->as(); + /// translate alias + if (alias.find(lhs_idf->shortName()) != alias.end()) + lhs_idf = alias.find(lhs_idf->shortName())->second->as(); - if (alias.find(rhs_idf->shortName()) != alias.end()) - rhs_idf = alias.find(rhs_idf->shortName())->second->as(); + if (alias.find(rhs_idf->shortName()) != alias.end()) + rhs_idf = alias.find(rhs_idf->shortName())->second->as(); - if (lhs_idf && rhs_idf && lhs_idf->shortName() == rhs_idf->shortName()) - return true; - } + if (lhs_idf && rhs_idf && lhs_idf->shortName() == rhs_idf->shortName()) + return true; } + return false; } diff --git a/src/Interpreters/Session.cpp b/src/Interpreters/Session.cpp index ede91b0df56..d92c6c462e7 100644 --- a/src/Interpreters/Session.cpp +++ b/src/Interpreters/Session.cpp @@ -129,17 +129,15 @@ public: return {session, true}; } - else - { - /// Use existing session. - const auto & session = it->second; - LOG_TRACE(log, "Reuse session from storage with session_id: {}, user_id: {}", key.second, key.first); + /// Use existing session. + const auto & session = it->second; - if (!isSharedPtrUnique(session)) - throw Exception(ErrorCodes::SESSION_IS_LOCKED, "Session {} is locked by a concurrent client", session_id); - return {session, false}; - } + LOG_TRACE(log, "Reuse session from storage with session_id: {}, user_id: {}", key.second, key.first); + + if (!isSharedPtrUnique(session)) + throw Exception(ErrorCodes::SESSION_IS_LOCKED, "Session {} is locked by a concurrent client", session_id); + return {session, false}; } void releaseSession(NamedSessionData & session) diff --git a/src/Interpreters/Set.cpp b/src/Interpreters/Set.cpp index f33418f45ac..bf6be4c0349 100644 --- a/src/Interpreters/Set.cpp +++ b/src/Interpreters/Set.cpp @@ -576,8 +576,7 @@ BoolMask MergeTreeSetIndex::checkInRange(const std::vector & key_ranges, lhs.get(row, f); if (f.isNull()) return 0; // +Inf == +Inf - else - return -1; + return -1; } return lhs.compareAt(row, 0, *rhs.column, 1); }; @@ -643,10 +642,9 @@ BoolMask MergeTreeSetIndex::checkInRange(const std::vector & key_ranges, /// Check if it's an empty range if (!left_included || !right_included) return {false, true}; - else if (left_lower != indices.end() && equals(*left_lower, left_point)) + if (left_lower != indices.end() && equals(*left_lower, left_point)) return {true, false}; - else - return {false, true}; + return {false, true}; } /// If there are more than one element in the range, it can always be false. Thus we only need to check if it may be true or not. @@ -656,7 +654,7 @@ BoolMask MergeTreeSetIndex::checkInRange(const std::vector & key_ranges, /// There is a point in between: left_lower + 1 return {true, true}; } - else if (left_lower + 1 == right_lower) + if (left_lower + 1 == right_lower) { /// Need to check if left_lower is a valid match, as left_point <= left_lower < right_point <= right_lower. /// Note: left_lower is valid. @@ -667,12 +665,10 @@ BoolMask MergeTreeSetIndex::checkInRange(const std::vector & key_ranges, /// Check if there is a match at the right boundary. return {right_included && right_lower != indices.end() && equals(*right_lower, right_point), true}; } - else // left_lower == right_lower - { - /// Need to check if right_point is a valid match, as left_point < right_point <= left_lower = right_lower. - /// Check if there is a match at the left boundary. - return {right_included && right_lower != indices.end() && equals(*right_lower, right_point), true}; - } + // left_lower == right_lower + /// Need to check if right_point is a valid match, as left_point < right_point <= left_lower = right_lower. + /// Check if there is a match at the left boundary. + return {right_included && right_lower != indices.end() && equals(*right_lower, right_point), true}; } bool MergeTreeSetIndex::hasMonotonicFunctionsChain() const diff --git a/src/Interpreters/StorageID.cpp b/src/Interpreters/StorageID.cpp index b3a504d7ef4..f49e5bc28d5 100644 --- a/src/Interpreters/StorageID.cpp +++ b/src/Interpreters/StorageID.cpp @@ -71,8 +71,7 @@ bool StorageID::operator==(const StorageID & rhs) const assertNotEmpty(); if (hasUUID() && rhs.hasUUID()) return uuid == rhs.uuid; - else - return std::tie(database_name, table_name) == std::tie(rhs.database_name, rhs.table_name); + return std::tie(database_name, table_name) == std::tie(rhs.database_name, rhs.table_name); } String StorageID::getFullTableName() const diff --git a/src/Interpreters/TemporaryDataOnDisk.cpp b/src/Interpreters/TemporaryDataOnDisk.cpp index 8f207b95e3e..81796678f24 100644 --- a/src/Interpreters/TemporaryDataOnDisk.cpp +++ b/src/Interpreters/TemporaryDataOnDisk.cpp @@ -70,7 +70,7 @@ std::unique_ptr TemporaryDataOnDisk::createRawStream(si auto holder = createCacheFile(max_file_size); return std::make_unique(std::move(holder)); } - else if (volume) + if (volume) { auto tmp_file = createRegularFile(max_file_size); return std::make_unique(std::move(tmp_file)); @@ -89,11 +89,12 @@ TemporaryFileStream & TemporaryDataOnDisk::createStream(const Block & header, si TemporaryFileStreamPtr & tmp_stream = streams.emplace_back(std::make_unique(std::move(holder), header, this)); return *tmp_stream; } - else if (volume) + if (volume) { auto tmp_file = createRegularFile(max_file_size); std::lock_guard lock(mutex); - TemporaryFileStreamPtr & tmp_stream = streams.emplace_back(std::make_unique(std::move(tmp_file), header, this)); + TemporaryFileStreamPtr & tmp_stream + = streams.emplace_back(std::make_unique(std::move(tmp_file), header, this)); return *tmp_stream; } diff --git a/src/Interpreters/TransactionLog.cpp b/src/Interpreters/TransactionLog.cpp index eb85467236e..69ef01d5f04 100644 --- a/src/Interpreters/TransactionLog.cpp +++ b/src/Interpreters/TransactionLog.cpp @@ -283,7 +283,7 @@ void TransactionLog::removeOldEntries() CSN new_tail_ptr = getOldestSnapshot(); if (new_tail_ptr < old_tail_ptr) throw Exception(ErrorCodes::LOGICAL_ERROR, "Got unexpected tail_ptr {}, oldest snapshot is {}, it's a bug", old_tail_ptr, new_tail_ptr); - else if (new_tail_ptr == old_tail_ptr) + if (new_tail_ptr == old_tail_ptr) return; /// (it's not supposed to fail with ZBADVERSION while there is only one host) diff --git a/src/Interpreters/TreeCNFConverter.cpp b/src/Interpreters/TreeCNFConverter.cpp index d2c7300c80c..a7db6aad29a 100644 --- a/src/Interpreters/TreeCNFConverter.cpp +++ b/src/Interpreters/TreeCNFConverter.cpp @@ -372,8 +372,7 @@ CNFQuery & CNFQuery::reduce() statements = filterCNFSubsets(statements); return *this; } - else - statements = new_statements; + statements = new_statements; } } diff --git a/src/Interpreters/castColumn.cpp b/src/Interpreters/castColumn.cpp index a779c9bc34d..3890c81934a 100644 --- a/src/Interpreters/castColumn.cpp +++ b/src/Interpreters/castColumn.cpp @@ -35,8 +35,7 @@ static ColumnPtr castColumn(CastType cast_type, const ColumnWithTypeAndName & ar if (cast_type == CastType::accurateOrNull) return func_cast->execute(arguments, makeNullable(type), arg.column->size()); - else - return func_cast->execute(arguments, type, arg.column->size()); + return func_cast->execute(arguments, type, arg.column->size()); } ColumnPtr castColumn(const ColumnWithTypeAndName & arg, const DataTypePtr & type, InternalCastFunctionCache * cache) diff --git a/src/Interpreters/convertFieldToType.cpp b/src/Interpreters/convertFieldToType.cpp index b831f6fad02..b4cfa9e8603 100644 --- a/src/Interpreters/convertFieldToType.cpp +++ b/src/Interpreters/convertFieldToType.cpp @@ -184,19 +184,20 @@ Field convertFieldToTypeImpl(const Field & src, const IDataType & type, const ID { return static_cast(static_cast(*from_type_hint).getTimeZone().toDayNum(src.safeGet()).toUnderType()); } - else if (which_type.isDate32() && which_from_type.isDateTime()) + if (which_type.isDate32() && which_from_type.isDateTime()) { - return static_cast(static_cast(*from_type_hint).getTimeZone().toDayNum(src.safeGet()).toUnderType()); + return static_cast( + static_cast(*from_type_hint).getTimeZone().toDayNum(src.safeGet()).toUnderType()); } - else if (which_type.isDateTime() && which_from_type.isDate()) + if (which_type.isDateTime() && which_from_type.isDate()) { return static_cast(type).getTimeZone().fromDayNum(DayNum(src.safeGet())); } - else if (which_type.isDateTime() && which_from_type.isDate32()) + if (which_type.isDateTime() && which_from_type.isDate32()) { return static_cast(type).getTimeZone().fromDayNum(DayNum(src.safeGet())); } - else if (which_type.isDateTime64() && which_from_type.isDate()) + if (which_type.isDateTime64() && which_from_type.isDate()) { const auto & date_time64_type = static_cast(type); const auto value = date_time64_type.getTimeZone().fromDayNum(DayNum(src.safeGet())); @@ -204,7 +205,7 @@ Field convertFieldToTypeImpl(const Field & src, const IDataType & type, const ID DecimalUtils::decimalFromComponentsWithMultiplier(value, 0, date_time64_type.getScaleMultiplier()), date_time64_type.getScale()); } - else if (which_type.isDateTime64() && which_from_type.isDate32()) + if (which_type.isDateTime64() && which_from_type.isDate32()) { const auto & date_time64_type = static_cast(type); const auto value = date_time64_type.getTimeZone().fromDayNum(ExtendedDayNum(static_cast(src.safeGet()))); @@ -212,30 +213,48 @@ Field convertFieldToTypeImpl(const Field & src, const IDataType & type, const ID DecimalUtils::decimalFromComponentsWithMultiplier(value, 0, date_time64_type.getScaleMultiplier()), date_time64_type.getScale()); } - else if (type.isValueRepresentedByNumber() && src.getType() != Field::Types::String) + if (type.isValueRepresentedByNumber() && src.getType() != Field::Types::String) { /// Bool is not represented in which_type, so we need to type it separately if (isInt64OrUInt64orBoolFieldType(src.getType()) && type.getName() == "Bool") return bool(src.safeGet()); - if (which_type.isUInt8()) return convertNumericType(src, type); - if (which_type.isUInt16()) return convertNumericType(src, type); - if (which_type.isUInt32()) return convertNumericType(src, type); - if (which_type.isUInt64()) return convertNumericType(src, type); - if (which_type.isUInt128()) return convertNumericType(src, type); - if (which_type.isUInt256()) return convertNumericType(src, type); - if (which_type.isInt8()) return convertNumericType(src, type); - if (which_type.isInt16()) return convertNumericType(src, type); - if (which_type.isInt32()) return convertNumericType(src, type); - if (which_type.isInt64()) return convertNumericType(src, type); - if (which_type.isInt128()) return convertNumericType(src, type); - if (which_type.isInt256()) return convertNumericType(src, type); - if (which_type.isFloat32()) return convertNumericType(src, type); - if (which_type.isFloat64()) return convertNumericType(src, type); - if (const auto * ptype = typeid_cast *>(&type)) return convertDecimalType(src, *ptype); - if (const auto * ptype = typeid_cast *>(&type)) return convertDecimalType(src, *ptype); - if (const auto * ptype = typeid_cast *>(&type)) return convertDecimalType(src, *ptype); - if (const auto * ptype = typeid_cast *>(&type)) return convertDecimalType(src, *ptype); + if (which_type.isUInt8()) + return convertNumericType(src, type); + if (which_type.isUInt16()) + return convertNumericType(src, type); + if (which_type.isUInt32()) + return convertNumericType(src, type); + if (which_type.isUInt64()) + return convertNumericType(src, type); + if (which_type.isUInt128()) + return convertNumericType(src, type); + if (which_type.isUInt256()) + return convertNumericType(src, type); + if (which_type.isInt8()) + return convertNumericType(src, type); + if (which_type.isInt16()) + return convertNumericType(src, type); + if (which_type.isInt32()) + return convertNumericType(src, type); + if (which_type.isInt64()) + return convertNumericType(src, type); + if (which_type.isInt128()) + return convertNumericType(src, type); + if (which_type.isInt256()) + return convertNumericType(src, type); + if (which_type.isFloat32()) + return convertNumericType(src, type); + if (which_type.isFloat64()) + return convertNumericType(src, type); + if (const auto * ptype = typeid_cast *>(&type)) + return convertDecimalType(src, *ptype); + if (const auto * ptype = typeid_cast *>(&type)) + return convertDecimalType(src, *ptype); + if (const auto * ptype = typeid_cast *>(&type)) + return convertDecimalType(src, *ptype); + if (const auto * ptype = typeid_cast *>(&type)) + return convertDecimalType(src, *ptype); if (which_type.isEnum() && (src.getType() == Field::Types::UInt64 || src.getType() == Field::Types::Int64)) { @@ -262,16 +281,16 @@ Field convertFieldToTypeImpl(const Field & src, const IDataType & type, const ID const auto scale_from = from_type.getScale(); const auto scale_to = to_type.getScale(); - const auto scale_multiplier_diff = scale_from > scale_to ? from_type.getScaleMultiplier() / to_type.getScaleMultiplier() : to_type.getScaleMultiplier() / from_type.getScaleMultiplier(); + const auto scale_multiplier_diff = scale_from > scale_to ? from_type.getScaleMultiplier() / to_type.getScaleMultiplier() + : to_type.getScaleMultiplier() / from_type.getScaleMultiplier(); if (scale_multiplier_diff == 1) /// Already in needed type. return src; /// in case if we need to make DateTime64(a) from DateTime64(b), a != b, we need to convert datetime value to the right scale - const UInt64 value = scale_from > scale_to ? from_type.getValue().value / scale_multiplier_diff : from_type.getValue().value * scale_multiplier_diff; - return DecimalField( - DecimalUtils::decimalFromComponentsWithMultiplier(value, 0, 1), - scale_to); + const UInt64 value = scale_from > scale_to ? from_type.getValue().value / scale_multiplier_diff + : from_type.getValue().value * scale_multiplier_diff; + return DecimalField(DecimalUtils::decimalFromComponentsWithMultiplier(value, 0, 1), scale_to); } /// For toDate('xxx') in 1::Int64, we CAST `src` to UInt64, which may @@ -379,8 +398,12 @@ Field convertFieldToTypeImpl(const Field & src, const IDataType & type, const ID size_t dst_tuple_size = type_tuple->getElements().size(); if (dst_tuple_size != src_tuple_size) - throw Exception(ErrorCodes::TYPE_MISMATCH, "Bad size of tuple in IN or VALUES section. " - "Expected size: {}, actual size: {}", dst_tuple_size, src_tuple_size); + throw Exception( + ErrorCodes::TYPE_MISMATCH, + "Bad size of tuple in IN or VALUES section. " + "Expected size: {}, actual size: {}", + dst_tuple_size, + src_tuple_size); Tuple res(dst_tuple_size); bool have_unconvertible_element = false; @@ -453,9 +476,7 @@ Field convertFieldToTypeImpl(const Field & src, const IDataType & type, const ID else if (const DataTypeAggregateFunction * agg_func_type = typeid_cast(&type)) { if (src.getType() != Field::Types::AggregateFunctionState) - throw Exception(ErrorCodes::TYPE_MISMATCH, - "Cannot convert {} to {}", - src.getTypeName(), agg_func_type->getName()); + throw Exception(ErrorCodes::TYPE_MISMATCH, "Cannot convert {} to {}", src.getTypeName(), agg_func_type->getName()); const auto & name = src.safeGet().name; if (agg_func_type->getName() != name) @@ -466,7 +487,7 @@ Field convertFieldToTypeImpl(const Field & src, const IDataType & type, const ID else if (isObjectDeprecated(type)) { if (src.getType() == Field::Types::Object) - return src; /// Already in needed type. + return src; /// Already in needed type. const auto * from_type_tuple = typeid_cast(from_type_hint); if (src.getType() == Field::Types::Tuple && from_type_tuple && from_type_tuple->haveExplicitNames()) @@ -475,9 +496,11 @@ Field convertFieldToTypeImpl(const Field & src, const IDataType & type, const ID const auto & tuple = src.safeGet(); if (names.size() != tuple.size()) - throw Exception(ErrorCodes::TYPE_MISMATCH, + throw Exception( + ErrorCodes::TYPE_MISMATCH, "Bad size of tuple in IN or VALUES section (while converting to Object). Expected size: {}, actual size: {}", - names.size(), tuple.size()); + names.size(), + tuple.size()); Object object; for (size_t i = 0; i < names.size(); ++i) @@ -497,8 +520,7 @@ Field convertFieldToTypeImpl(const Field & src, const IDataType & type, const ID const auto & value = map_entry[1]; if (key.getType() != Field::Types::String) - throw Exception(ErrorCodes::TYPE_MISMATCH, - "Cannot convert from Map with key of type {} to Object", key.getTypeName()); + throw Exception(ErrorCodes::TYPE_MISMATCH, "Cannot convert from Map with key of type {} to Object", key.getTypeName()); object[key.safeGet()] = value; } @@ -526,7 +548,7 @@ Field convertFieldToTypeImpl(const Field & src, const IDataType & type, const ID else if (isObject(type)) { if (src.getType() == Field::Types::Object) - return src; /// Already in needed type. + return src; /// Already in needed type. /// TODO: add conversion from Map/Tuple to Object. } @@ -594,7 +616,7 @@ Field convertFieldToType(const Field & from_value, const IDataType & to_type, co if (const auto * low_cardinality_type = typeid_cast(&to_type)) return convertFieldToType(from_value, *low_cardinality_type->getDictionaryType(), from_type_hint, format_settings); - else if (const auto * nullable_type = typeid_cast(&to_type)) + if (const auto * nullable_type = typeid_cast(&to_type)) { const IDataType & nested_type = *nullable_type->getNestedType(); @@ -606,8 +628,7 @@ Field convertFieldToType(const Field & from_value, const IDataType & to_type, co return from_value; return convertFieldToTypeImpl(from_value, nested_type, from_type_hint, format_settings); } - else - return convertFieldToTypeImpl(from_value, to_type, from_type_hint, format_settings); + return convertFieldToTypeImpl(from_value, to_type, from_type_hint, format_settings); } diff --git a/src/Interpreters/evaluateConstantExpression.cpp b/src/Interpreters/evaluateConstantExpression.cpp index 4e2d68ad6fa..677e0d7b2ec 100644 --- a/src/Interpreters/evaluateConstantExpression.cpp +++ b/src/Interpreters/evaluateConstantExpression.cpp @@ -315,7 +315,7 @@ namespace --limit; return analyzeEquals(identifier, literal, expr); } - else if (fn->name == "in") + if (fn->name == "in") { const auto * left = fn->arguments->children.front().get(); const auto * right = fn->arguments->children.back().get(); @@ -385,7 +385,7 @@ namespace return result; } - else if (fn->name == "or") + if (fn->name == "or") { const auto * args = fn->children.front()->as(); @@ -411,7 +411,7 @@ namespace return result; } - else if (fn->name == "and") + if (fn->name == "and") { const auto * args = fn->children.front()->as(); @@ -856,8 +856,7 @@ std::optional evaluateExpressionOverConstantCondition(const ASTPtr & nod // Check if it's always true or false. if (literal->value.getType() == Field::Types::UInt64 && literal->value.safeGet() == 0) return {result}; - else - return {}; + return {}; } return {result}; diff --git a/src/Interpreters/executeDDLQueryOnCluster.cpp b/src/Interpreters/executeDDLQueryOnCluster.cpp index 0eb703b34ec..d7d9da2a367 100644 --- a/src/Interpreters/executeDDLQueryOnCluster.cpp +++ b/src/Interpreters/executeDDLQueryOnCluster.cpp @@ -304,17 +304,15 @@ Block DDLQueryStatusSource::getSampleBlock(ContextPtr context_, bool hosts_to_wa {std::make_shared(), "num_hosts_active"}, }; } - else - { - return Block{ - {std::make_shared(), "host"}, - {std::make_shared(), "port"}, - {maybe_make_nullable(std::make_shared()), "status"}, - {maybe_make_nullable(std::make_shared()), "error"}, - {std::make_shared(), "num_hosts_remaining"}, - {std::make_shared(), "num_hosts_active"}, - }; - } + + return Block{ + {std::make_shared(), "host"}, + {std::make_shared(), "port"}, + {maybe_make_nullable(std::make_shared()), "status"}, + {maybe_make_nullable(std::make_shared()), "error"}, + {std::make_shared(), "num_hosts_remaining"}, + {std::make_shared(), "num_hosts_active"}, + }; } DDLQueryStatusSource::DDLQueryStatusSource( @@ -631,8 +629,7 @@ IProcessor::Status DDLQueryStatusSource::prepare() output.finish(); return Status::Finished; } - else - return ISource::prepare(); + return ISource::prepare(); } Strings DDLQueryStatusSource::getNewAndUpdate(const Strings & current_list_of_finished_hosts) diff --git a/src/Interpreters/executeQuery.cpp b/src/Interpreters/executeQuery.cpp index 11d93fc39b8..5550d57cb8e 100644 --- a/src/Interpreters/executeQuery.cpp +++ b/src/Interpreters/executeQuery.cpp @@ -877,8 +877,8 @@ static std::tuple executeQueryImpl( throw Exception(ErrorCodes::LOGICAL_ERROR, "Inconsistent AST formatting: the query:\n{}\ncannot parse query back from {}", formatted1, std::string_view(begin, end-begin)); - else - throw; + + throw; } chassert(ast2); diff --git a/src/Interpreters/inplaceBlockConversions.cpp b/src/Interpreters/inplaceBlockConversions.cpp index 68254768a7d..a7e507330be 100644 --- a/src/Interpreters/inplaceBlockConversions.cpp +++ b/src/Interpreters/inplaceBlockConversions.cpp @@ -145,7 +145,7 @@ ASTPtr convertRequiredExpressions(Block & block, const NamesAndTypesList & requi if (!block.has(required_column.name)) continue; - auto column_in_block = block.getByName(required_column.name); + const auto & column_in_block = block.getByName(required_column.name); if (column_in_block.type->equals(*required_column.type)) continue; diff --git a/src/Interpreters/loadMetadata.cpp b/src/Interpreters/loadMetadata.cpp index 8eaf26672e2..4f72c29a625 100644 --- a/src/Interpreters/loadMetadata.cpp +++ b/src/Interpreters/loadMetadata.cpp @@ -270,15 +270,13 @@ LoadTaskPtrs loadMetadata(ContextMutablePtr context, const String & default_data // Do NOT wait, just return tasks for continuation or later wait. return joinTasks(load_tasks, startup_tasks); } - else - { - // NOTE: some tables can still be started up in the "loading" phase if they are required by dependencies during loading of other tables - LOG_INFO(log, "Start synchronous loading of databases"); - waitLoad(TablesLoaderForegroundPoolId, load_tasks); // First prioritize, schedule and wait all the load table tasks - LOG_INFO(log, "Start synchronous startup of databases"); - waitLoad(TablesLoaderForegroundPoolId, startup_tasks); // Only then prioritize, schedule and wait all the startup tasks - return {}; - } + + // NOTE: some tables can still be started up in the "loading" phase if they are required by dependencies during loading of other tables + LOG_INFO(log, "Start synchronous loading of databases"); + waitLoad(TablesLoaderForegroundPoolId, load_tasks); // First prioritize, schedule and wait all the load table tasks + LOG_INFO(log, "Start synchronous startup of databases"); + waitLoad(TablesLoaderForegroundPoolId, startup_tasks); // Only then prioritize, schedule and wait all the startup tasks + return {}; } static void loadSystemDatabaseImpl(ContextMutablePtr context, const String & database_name, const String & default_engine) diff --git a/src/Interpreters/replaceForPositionalArguments.cpp b/src/Interpreters/replaceForPositionalArguments.cpp index ee967f45c74..251629d4208 100644 --- a/src/Interpreters/replaceForPositionalArguments.cpp +++ b/src/Interpreters/replaceForPositionalArguments.cpp @@ -79,13 +79,11 @@ bool replaceForPositionalArguments(ASTPtr & argument, const ASTSelectQuery * sel "Illegal value (aggregate function) for positional argument in {}", ASTSelectQuery::expressionToString(expression)); } - else + + if (function->arguments) { - if (function->arguments) - { - for (const auto & arg : function->arguments->children) - throw_if_aggregate_function(arg); - } + for (const auto & arg : function->arguments->children) + throw_if_aggregate_function(arg); } } }; diff --git a/src/Parsers/ASTDropQuery.cpp b/src/Parsers/ASTDropQuery.cpp index cf912d66b44..593ca37aa2a 100644 --- a/src/Parsers/ASTDropQuery.cpp +++ b/src/Parsers/ASTDropQuery.cpp @@ -18,12 +18,11 @@ String ASTDropQuery::getID(char delim) const { if (kind == ASTDropQuery::Kind::Drop) return "DropQuery" + (delim + getDatabase()) + delim + getTable(); - else if (kind == ASTDropQuery::Kind::Detach) + if (kind == ASTDropQuery::Kind::Detach) return "DetachQuery" + (delim + getDatabase()) + delim + getTable(); - else if (kind == ASTDropQuery::Kind::Truncate) + if (kind == ASTDropQuery::Kind::Truncate) return "TruncateQuery" + (delim + getDatabase()) + delim + getTable(); - else - throw Exception(ErrorCodes::SYNTAX_ERROR, "Not supported kind of drop query."); + throw Exception(ErrorCodes::SYNTAX_ERROR, "Not supported kind of drop query."); } ASTPtr ASTDropQuery::clone() const diff --git a/src/Parsers/ASTIdentifier.cpp b/src/Parsers/ASTIdentifier.cpp index f466e10d7d8..902432f5ef3 100644 --- a/src/Parsers/ASTIdentifier.cpp +++ b/src/Parsers/ASTIdentifier.cpp @@ -198,13 +198,13 @@ ASTPtr ASTTableIdentifier::clone() const StorageID ASTTableIdentifier::getTableId() const { if (name_parts.size() == 2) return {name_parts[0], name_parts[1], uuid}; - else return {{}, name_parts[0], uuid}; + return {{}, name_parts[0], uuid}; } String ASTTableIdentifier::getDatabaseName() const { if (name_parts.size() == 2) return name_parts[0]; - else return {}; + return {}; } ASTPtr ASTTableIdentifier::getTable() const @@ -216,17 +216,15 @@ ASTPtr ASTTableIdentifier::getTable() const if (name_parts[0].empty()) return std::make_shared("", children[1]->clone()); - else - return std::make_shared("", children[0]->clone()); + return std::make_shared("", children[0]->clone()); } - else if (name_parts.size() == 1) + if (name_parts.size() == 1) { if (name_parts[0].empty()) return std::make_shared("", children[0]->clone()); - else - return std::make_shared(name_parts[0]); + return std::make_shared(name_parts[0]); } - else return {}; + return {}; } ASTPtr ASTTableIdentifier::getDatabase() const @@ -235,10 +233,9 @@ ASTPtr ASTTableIdentifier::getDatabase() const { if (name_parts[0].empty()) return std::make_shared("", children[0]->clone()); - else - return std::make_shared(name_parts[0]); + return std::make_shared(name_parts[0]); } - else return {}; + return {}; } void ASTTableIdentifier::resetTable(const String & database_name, const String & table_name) diff --git a/src/Parsers/ASTSampleRatio.cpp b/src/Parsers/ASTSampleRatio.cpp index 03a4c9adf23..608bf18bb1e 100644 --- a/src/Parsers/ASTSampleRatio.cpp +++ b/src/Parsers/ASTSampleRatio.cpp @@ -31,8 +31,7 @@ String ASTSampleRatio::toString(Rational ratio) { if (ratio.denominator == 1) return toString(ratio.numerator); - else - return toString(ratio.numerator) + " / " + toString(ratio.denominator); + return toString(ratio.numerator) + " / " + toString(ratio.denominator); } void ASTSampleRatio::formatImpl(const IAST::FormatSettings & settings, IAST::FormatState &, IAST::FormatStateStacked) const diff --git a/src/Parsers/ASTSelectQuery.cpp b/src/Parsers/ASTSelectQuery.cpp index 244f0bd4c8a..8b1f82e9ee8 100644 --- a/src/Parsers/ASTSelectQuery.cpp +++ b/src/Parsers/ASTSelectQuery.cpp @@ -400,9 +400,9 @@ static String getTableExpressionAlias(const ASTTableExpression * table_expressio { if (table_expression->subquery) return table_expression->subquery->tryGetAlias(); - else if (table_expression->table_function) + if (table_expression->table_function) return table_expression->table_function->tryGetAlias(); - else if (table_expression->database_and_table_name) + if (table_expression->database_and_table_name) return table_expression->database_and_table_name->tryGetAlias(); return String(); diff --git a/src/Parsers/ASTSelectWithUnionQuery.cpp b/src/Parsers/ASTSelectWithUnionQuery.cpp index d131a54d9b1..811704171bd 100644 --- a/src/Parsers/ASTSelectWithUnionQuery.cpp +++ b/src/Parsers/ASTSelectWithUnionQuery.cpp @@ -35,21 +35,21 @@ void ASTSelectWithUnionQuery::formatQueryImpl(const FormatSettings & settings, F { if (mode == SelectUnionMode::UNION_DEFAULT) return "UNION"; - else if (mode == SelectUnionMode::UNION_ALL) + if (mode == SelectUnionMode::UNION_ALL) return "UNION ALL"; - else if (mode == SelectUnionMode::UNION_DISTINCT) + if (mode == SelectUnionMode::UNION_DISTINCT) return "UNION DISTINCT"; - else if (mode == SelectUnionMode::EXCEPT_DEFAULT) + if (mode == SelectUnionMode::EXCEPT_DEFAULT) return "EXCEPT"; - else if (mode == SelectUnionMode::EXCEPT_ALL) + if (mode == SelectUnionMode::EXCEPT_ALL) return "EXCEPT ALL"; - else if (mode == SelectUnionMode::EXCEPT_DISTINCT) + if (mode == SelectUnionMode::EXCEPT_DISTINCT) return "EXCEPT DISTINCT"; - else if (mode == SelectUnionMode::INTERSECT_DEFAULT) + if (mode == SelectUnionMode::INTERSECT_DEFAULT) return "INTERSECT"; - else if (mode == SelectUnionMode::INTERSECT_ALL) + if (mode == SelectUnionMode::INTERSECT_ALL) return "INTERSECT ALL"; - else if (mode == SelectUnionMode::INTERSECT_DISTINCT) + if (mode == SelectUnionMode::INTERSECT_DISTINCT) return "INTERSECT DISTINCT"; return ""; }; diff --git a/src/Parsers/Access/ParserCreateQuotaQuery.cpp b/src/Parsers/Access/ParserCreateQuotaQuery.cpp index ddf4e9ecda5..61e0bee08e7 100644 --- a/src/Parsers/Access/ParserCreateQuotaQuery.cpp +++ b/src/Parsers/Access/ParserCreateQuotaQuery.cpp @@ -115,8 +115,7 @@ namespace { if (f.getType() == Field::Types::String) return parseWithSizeSuffix(boost::algorithm::trim_copy(f.safeGet())); - else - return applyVisitor(FieldVisitorConvertToNumber(), f); + return applyVisitor(FieldVisitorConvertToNumber(), f); } bool parseMaxValue(IParserBase::Pos & pos, Expected & expected, QuotaType quota_type, QuotaValue & max_value) diff --git a/src/Parsers/Access/ParserGrantQuery.cpp b/src/Parsers/Access/ParserGrantQuery.cpp index e08e1ddae72..e29cf11273b 100644 --- a/src/Parsers/Access/ParserGrantQuery.cpp +++ b/src/Parsers/Access/ParserGrantQuery.cpp @@ -224,14 +224,14 @@ namespace if (!element.anyColumn()) throw Exception(ErrorCodes::INVALID_GRANT, "{} cannot be granted on the column level", old_flags.toString()); - else if (!element.anyTable()) + if (!element.anyTable()) throw Exception(ErrorCodes::INVALID_GRANT, "{} cannot be granted on the table level", old_flags.toString()); - else if (!element.anyDatabase()) + if (!element.anyDatabase()) throw Exception(ErrorCodes::INVALID_GRANT, "{} cannot be granted on the database level", old_flags.toString()); - else if (!element.anyParameter()) + if (!element.anyParameter()) throw Exception(ErrorCodes::INVALID_GRANT, "{} cannot be granted on the global with parameter level", old_flags.toString()); - else - throw Exception(ErrorCodes::INVALID_GRANT, "{} cannot be granted", old_flags.toString()); + + throw Exception(ErrorCodes::INVALID_GRANT, "{} cannot be granted", old_flags.toString()); }); } diff --git a/src/Parsers/Access/ParserRowPolicyName.cpp b/src/Parsers/Access/ParserRowPolicyName.cpp index 887cab30694..9128dbb659a 100644 --- a/src/Parsers/Access/ParserRowPolicyName.cpp +++ b/src/Parsers/Access/ParserRowPolicyName.cpp @@ -29,14 +29,12 @@ namespace bool wildcard = false; bool default_database = false; - if (!parseDatabaseAndTableNameOrAsterisks(pos, expected, res_database, res_table_name, wildcard, default_database) || (res_database.empty() && res_table_name.empty() && !default_database)) - { + if (!parseDatabaseAndTableNameOrAsterisks(pos, expected, res_database, res_table_name, wildcard, default_database) + || (res_database.empty() && res_table_name.empty() && !default_database)) return false; - } - else if (res_table_name.empty()) - { + + if (res_table_name.empty()) res_table_name = RowPolicyName::ANY_TABLE_MARK; - } /// If table is specified without DB it cannot be followed by Keyword::ON /// (but can be followed by Keyword::ON CLUSTER). diff --git a/src/Parsers/Access/ParserSettingsProfileElement.cpp b/src/Parsers/Access/ParserSettingsProfileElement.cpp index 78002d1b425..88ee4af3cec 100644 --- a/src/Parsers/Access/ParserSettingsProfileElement.cpp +++ b/src/Parsers/Access/ParserSettingsProfileElement.cpp @@ -104,18 +104,17 @@ namespace writability = SettingConstraintWritability::CONST; return true; } - else if (ParserKeyword{Keyword::WRITABLE}.ignore(pos, expected)) + if (ParserKeyword{Keyword::WRITABLE}.ignore(pos, expected)) { writability = SettingConstraintWritability::WRITABLE; return true; } - else if (ParserKeyword{Keyword::CHANGEABLE_IN_READONLY}.ignore(pos, expected)) + if (ParserKeyword{Keyword::CHANGEABLE_IN_READONLY}.ignore(pos, expected)) { writability = SettingConstraintWritability::CHANGEABLE_IN_READONLY; return true; } - else - return false; + return false; }); } diff --git a/src/Parsers/ExpressionElementParsers.cpp b/src/Parsers/ExpressionElementParsers.cpp index f376497ff9f..31efcb16f02 100644 --- a/src/Parsers/ExpressionElementParsers.cpp +++ b/src/Parsers/ExpressionElementParsers.cpp @@ -196,13 +196,13 @@ bool ParserIdentifier::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) ++pos; return true; } - else if (pos->type == TokenType::BareWord) + if (pos->type == TokenType::BareWord) { node = std::make_shared(String(pos->begin, pos->end)); ++pos; return true; } - else if (allow_query_parameter && pos->type == TokenType::OpeningCurlyBrace) + if (allow_query_parameter && pos->type == TokenType::OpeningCurlyBrace) { ++pos; if (pos->type != TokenType::BareWord) @@ -480,10 +480,8 @@ bool ParserWindowReference::parseImpl(Pos & pos, ASTPtr & node, Expected & expec function.window_name = getIdentifierName(window_name_ast); return true; } - else - { - return false; - } + + return false; } // Variant 2: @@ -949,12 +947,10 @@ bool ParserCastOperator::parseImpl(Pos & pos, ASTPtr & node, Expected & expected node = createFunctionCast(string_literal, type_ast); return true; } - else - { - auto literal = std::make_shared(String(data_begin, data_size)); - node = createFunctionCast(literal, type_ast); - return true; - } + + auto literal = std::make_shared(String(data_begin, data_size)); + node = createFunctionCast(literal, type_ast); + return true; } return false; @@ -969,8 +965,7 @@ bool ParserNull::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) node = std::make_shared(Null()); return true; } - else - return false; + return false; } @@ -981,13 +976,12 @@ bool ParserBool::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) node = std::make_shared(true); return true; } - else if (ParserKeyword(Keyword::FALSE_KEYWORD).parse(pos, node, expected)) + if (ParserKeyword(Keyword::FALSE_KEYWORD).parse(pos, node, expected)) { node = std::make_shared(false); return true; } - else - return false; + return false; } static bool parseNumber(char * buffer, size_t size, bool negative, int base, Field & res) @@ -1120,8 +1114,7 @@ bool ParserNumber::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) return true; } - else - return false; + return false; } /// hexadecimal @@ -1338,7 +1331,7 @@ bool ParserCollectionOfLiterals::parseImpl(Pos & pos, ASTPtr & node, layers.back().arr.push_back(literal->value); continue; } - else if (pos->type == TokenType::Comma) + if (pos->type == TokenType::Comma) { ++pos; } @@ -1739,7 +1732,7 @@ bool ParserColumnsTransformers::parseImpl(Pos & pos, ASTPtr & node, Expected & e node = std::move(res); return true; } - else if (allowed_transformers.isSet(ColumnTransformer::EXCEPT) && except.ignore(pos, expected)) + if (allowed_transformers.isSet(ColumnTransformer::EXCEPT) && except.ignore(pos, expected)) { if (strict.ignore(pos, expected)) is_strict = true; @@ -1784,7 +1777,7 @@ bool ParserColumnsTransformers::parseImpl(Pos & pos, ASTPtr & node, Expected & e node = std::move(res); return true; } - else if (allowed_transformers.isSet(ColumnTransformer::REPLACE) && replace.ignore(pos, expected)) + if (allowed_transformers.isSet(ColumnTransformer::REPLACE) && replace.ignore(pos, expected)) { if (strict.ignore(pos, expected)) is_strict = true; diff --git a/src/Parsers/ExpressionListParsers.cpp b/src/Parsers/ExpressionListParsers.cpp index aab88c300b8..6d4a2e57d10 100644 --- a/src/Parsers/ExpressionListParsers.cpp +++ b/src/Parsers/ExpressionListParsers.cpp @@ -100,7 +100,7 @@ bool ParserUnionList::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) union_modes.push_back(SelectUnionMode::UNION_DEFAULT); return true; } - else if (s_except_parser.check(pos, expected)) + if (s_except_parser.check(pos, expected)) { if (s_all_parser.check(pos, expected)) union_modes.push_back(SelectUnionMode::EXCEPT_ALL); @@ -110,7 +110,7 @@ bool ParserUnionList::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) union_modes.push_back(SelectUnionMode::EXCEPT_DEFAULT); return true; } - else if (s_intersect_parser.check(pos, expected)) + if (s_intersect_parser.check(pos, expected)) { if (s_all_parser.check(pos, expected)) union_modes.push_back(SelectUnionMode::INTERSECT_ALL); @@ -137,7 +137,7 @@ static bool parseOperator(IParser::Pos & pos, std::string_view op, Expected & ex { return ParserKeyword::createDeprecated(op).ignore(pos, expected); } - else if (op.length() == pos->size() && 0 == memcmp(op.data(), pos->begin, pos->size())) + if (op.length() == pos->size() && 0 == memcmp(op.data(), pos->begin, pos->size())) { ++pos; return true; @@ -298,12 +298,10 @@ ASTPtr makeBetweenOperator(bool negative, ASTs arguments) auto f_right_expr = makeASTFunction("greater", arguments[0], arguments[2]); return makeASTFunction("or", f_left_expr, f_right_expr); } - else - { - auto f_left_expr = makeASTFunction("greaterOrEquals", arguments[0], arguments[1]); - auto f_right_expr = makeASTFunction("lessOrEquals", arguments[0], arguments[2]); - return makeASTFunction("and", f_left_expr, f_right_expr); - } + + auto f_left_expr = makeASTFunction("greaterOrEquals", arguments[0], arguments[1]); + auto f_right_expr = makeASTFunction("lessOrEquals", arguments[0], arguments[2]); + return makeASTFunction("and", f_left_expr, f_right_expr); } ParserExpressionWithOptionalAlias::ParserExpressionWithOptionalAlias(bool allow_alias_without_as_keyword, bool is_table_function, bool allow_trailing_commas) @@ -1396,11 +1394,9 @@ public: state = 2; return true; } - else - { - state = 1; - pos = begin; - } + + state = 1; + pos = begin; } if (state == 1) @@ -2272,9 +2268,9 @@ std::unique_ptr getFunctionLayer(ASTPtr identifier, bool is_table_functio { if (function_name_lowercase == "view") return std::make_unique(false); - else if (function_name_lowercase == "viewifpermitted") + if (function_name_lowercase == "viewifpermitted") return std::make_unique(true); - else if (function_name_lowercase == "kql") + if (function_name_lowercase == "kql") return std::make_unique(); } @@ -2283,33 +2279,32 @@ std::unique_ptr getFunctionLayer(ASTPtr identifier, bool is_table_functio if (function_name_lowercase == "cast") return std::make_unique(); - else if (function_name_lowercase == "extract") + if (function_name_lowercase == "extract") return std::make_unique(); - else if (function_name_lowercase == "substring") + if (function_name_lowercase == "substring") return std::make_unique(); - else if (function_name_lowercase == "position") + if (function_name_lowercase == "position") return std::make_unique(); - else if (function_name_lowercase == "exists") + if (function_name_lowercase == "exists") return std::make_unique(); - else if (function_name_lowercase == "trim") + if (function_name_lowercase == "trim") return std::make_unique(false, false); - else if (function_name_lowercase == "ltrim") + if (function_name_lowercase == "ltrim") return std::make_unique(true, false); - else if (function_name_lowercase == "rtrim") + if (function_name_lowercase == "rtrim") return std::make_unique(false, true); - else if (function_name_lowercase == "dateadd" || function_name_lowercase == "date_add" - || function_name_lowercase == "timestampadd" || function_name_lowercase == "timestamp_add") + if (function_name_lowercase == "dateadd" || function_name_lowercase == "date_add" || function_name_lowercase == "timestampadd" + || function_name_lowercase == "timestamp_add") return std::make_unique("plus"); - else if (function_name_lowercase == "datesub" || function_name_lowercase == "date_sub" - || function_name_lowercase == "timestampsub" || function_name_lowercase == "timestamp_sub") + if (function_name_lowercase == "datesub" || function_name_lowercase == "date_sub" || function_name_lowercase == "timestampsub" + || function_name_lowercase == "timestamp_sub") return std::make_unique("minus"); - else if (function_name_lowercase == "datediff" || function_name_lowercase == "date_diff" - || function_name_lowercase == "timestampdiff" || function_name_lowercase == "timestamp_diff") + if (function_name_lowercase == "datediff" || function_name_lowercase == "date_diff" || function_name_lowercase == "timestampdiff" + || function_name_lowercase == "timestamp_diff") return std::make_unique(); - else if (function_name_lowercase == "grouping") + if (function_name_lowercase == "grouping") return std::make_unique(function_name_lowercase, allow_function_parameters_); - else - return std::make_unique(function_name, allow_function_parameters_, identifier->as()->compound()); + return std::make_unique(function_name, allow_function_parameters_, identifier->as()->compound()); } @@ -2400,10 +2395,8 @@ bool ParserFunction::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) start->is_table_function = is_table_function; return ParserExpressionImpl().parse(std::move(start), pos, node, expected); } - else - { - return false; - } + + return false; } bool ParserExpressionWithOptionalArguments::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) @@ -2572,10 +2565,8 @@ Action ParserExpressionImpl::tryParseOperand(Layers & layers, IParser::Pos & pos layers.back()->pushOperand(tmp); return Action::OPERAND; } - else - { - pos = old_pos; - } + + pos = old_pos; } } } @@ -2616,10 +2607,8 @@ Action ParserExpressionImpl::tryParseOperand(Layers & layers, IParser::Pos & pos layers.back()->pushOperand(std::move(function)); return Action::OPERATOR; } - else - { - pos = old_pos; - } + + pos = old_pos; } /// ignore all leading plus @@ -2661,7 +2650,7 @@ Action ParserExpressionImpl::tryParseOperand(Layers & layers, IParser::Pos & pos layers.push_back(std::make_unique()); return Action::OPERAND; } - else if (current_checkpoint != Checkpoint::Case && parseOperator(pos, toStringView(Keyword::CASE), expected)) + if (current_checkpoint != Checkpoint::Case && parseOperator(pos, toStringView(Keyword::CASE), expected)) { layers.back()->saved_checkpoint = {old_pos, Checkpoint::Case}; layers.push_back(std::make_unique()); diff --git a/src/Parsers/FunctionSecretArgumentsFinder.h b/src/Parsers/FunctionSecretArgumentsFinder.h index fa1355937ee..9277093c608 100644 --- a/src/Parsers/FunctionSecretArgumentsFinder.h +++ b/src/Parsers/FunctionSecretArgumentsFinder.h @@ -256,7 +256,7 @@ protected: findSecretNamedArgument("account_key", 1); return; } - else if (is_cluster_function && isNamedCollectionName(1)) + if (is_cluster_function && isNamedCollectionName(1)) { /// azureBlobStorageCluster(cluster, named_collection, ..., account_key = 'account_key', ...) if (maskAzureConnectionString(-1, true, 2)) diff --git a/src/Parsers/IParser.h b/src/Parsers/IParser.h index cb3684bfe5d..9ffefb945b6 100644 --- a/src/Parsers/IParser.h +++ b/src/Parsers/IParser.h @@ -178,8 +178,7 @@ public: pos = begin; return false; } - else - return true; + return true; } /** The same, but doesn't move the position even if parsing was successful. diff --git a/src/Parsers/Kusto/KustoFunctions/IParserKQLFunction.cpp b/src/Parsers/Kusto/KustoFunctions/IParserKQLFunction.cpp index affce53fbc7..a16f7db345f 100644 --- a/src/Parsers/Kusto/KustoFunctions/IParserKQLFunction.cpp +++ b/src/Parsers/Kusto/KustoFunctions/IParserKQLFunction.cpp @@ -24,9 +24,9 @@ constexpr DB::TokenType determineClosingPair(const DB::TokenType token_type) { if (token_type == DB::TokenType::OpeningCurlyBrace) return DB::TokenType::ClosingCurlyBrace; - else if (token_type == DB::TokenType::OpeningRoundBracket) + if (token_type == DB::TokenType::OpeningRoundBracket) return DB::TokenType::ClosingRoundBracket; - else if (token_type == DB::TokenType::OpeningSquareBracket) + if (token_type == DB::TokenType::OpeningSquareBracket) return DB::TokenType::ClosingSquareBracket; throw DB::Exception(DB::ErrorCodes::NOT_IMPLEMENTED, "Unhandled token: {}", magic_enum::enum_name(token_type)); diff --git a/src/Parsers/Kusto/KustoFunctions/KQLDataTypeFunctions.cpp b/src/Parsers/Kusto/KustoFunctions/KQLDataTypeFunctions.cpp index 3b1f96b4ea6..dd2f82cf144 100644 --- a/src/Parsers/Kusto/KustoFunctions/KQLDataTypeFunctions.cpp +++ b/src/Parsers/Kusto/KustoFunctions/KQLDataTypeFunctions.cpp @@ -141,11 +141,9 @@ bool DatatypeInt::convertImpl(String & out, IParser::Pos & pos) ++pos; if (pos->type == TokenType::QuotedIdentifier || pos->type == TokenType::StringLiteral) throw Exception(ErrorCodes::BAD_ARGUMENTS, "String is not parsed as int literal."); - else - { - auto arg = getConvertedArgument(fn_name, pos); - out = std::format("toInt32({})", arg); - } + + auto arg = getConvertedArgument(fn_name, pos); + out = std::format("toInt32({})", arg); return true; } @@ -163,11 +161,9 @@ bool DatatypeReal::convertImpl(String & out, IParser::Pos & pos) ++pos; if (pos->type == TokenType::QuotedIdentifier || pos->type == TokenType::StringLiteral) throw Exception(ErrorCodes::BAD_ARGUMENTS, "String is not parsed as double literal."); - else - { - auto arg = getConvertedArgument(fn_name, pos); - out = std::format("toFloat64({})", arg); - } + + auto arg = getConvertedArgument(fn_name, pos); + out = std::format("toFloat64({})", arg); return true; } diff --git a/src/Parsers/Kusto/KustoFunctions/KQLDynamicFunctions.cpp b/src/Parsers/Kusto/KustoFunctions/KQLDynamicFunctions.cpp index e90be363e4b..49e863178f3 100644 --- a/src/Parsers/Kusto/KustoFunctions/KQLDynamicFunctions.cpp +++ b/src/Parsers/Kusto/KustoFunctions/KQLDynamicFunctions.cpp @@ -272,8 +272,7 @@ bool Repeat::convertImpl(String & out, IParser::Pos & pos) if (count.empty()) throw Exception(ErrorCodes::SYNTAX_ERROR, "number of arguments do not match in function: {}", function_name); - else - out = "if(" + count + " < 0, [NULL], " + std::format("arrayWithConstant(abs({1}), {0}))", value, count); + out = "if(" + count + " < 0, [NULL], " + std::format("arrayWithConstant(abs({1}), {0}))", value, count); return true; } diff --git a/src/Parsers/Kusto/KustoFunctions/KQLStringFunctions.cpp b/src/Parsers/Kusto/KustoFunctions/KQLStringFunctions.cpp index 991a3139fcb..dcdd4273896 100644 --- a/src/Parsers/Kusto/KustoFunctions/KQLStringFunctions.cpp +++ b/src/Parsers/Kusto/KustoFunctions/KQLStringFunctions.cpp @@ -675,9 +675,8 @@ bool SubString::convertImpl(String & out, IParser::Pos & pos) if (starting_index.empty()) throw Exception(ErrorCodes::SYNTAX_ERROR, "number of arguments do not match in function: {}", fn_name); - else - out = "if(toInt64(length(" + source + ")) <= 0, '', substr(" + source + ", " + "((" + starting_index + "% toInt64(length(" - + source + ")) + toInt64(length(" + source + "))) % toInt64(length(" + source + "))) + 1, " + length + ") )"; + out = "if(toInt64(length(" + source + ")) <= 0, '', substr(" + source + ", " + "((" + starting_index + "% toInt64(length(" + source + + ")) + toInt64(length(" + source + "))) % toInt64(length(" + source + "))) + 1, " + length + ") )"; } else out = "if(toInt64(length(" + source + ")) <= 0, '', substr(" + source + "," + "((" + starting_index + "% toInt64(length(" + source diff --git a/src/Parsers/Kusto/ParserKQLQuery.cpp b/src/Parsers/Kusto/ParserKQLQuery.cpp index 626512b6ea1..f89b4baa0e0 100644 --- a/src/Parsers/Kusto/ParserKQLQuery.cpp +++ b/src/Parsers/Kusto/ParserKQLQuery.cpp @@ -309,28 +309,27 @@ std::unique_ptr ParserKQLQuery::getOperator(String & op_name) { if (op_name == "filter" || op_name == "where") return std::make_unique(); - else if (op_name == "limit" || op_name == "take") + if (op_name == "limit" || op_name == "take") return std::make_unique(); - else if (op_name == "project") + if (op_name == "project") return std::make_unique(); - else if (op_name == "distinct") + if (op_name == "distinct") return std::make_unique(); - else if (op_name == "extend") + if (op_name == "extend") return std::make_unique(); - else if (op_name == "sort by" || op_name == "order by") + if (op_name == "sort by" || op_name == "order by") return std::make_unique(); - else if (op_name == "summarize") + if (op_name == "summarize") return std::make_unique(); - else if (op_name == "table") + if (op_name == "table") return std::make_unique(); - else if (op_name == "make-series") + if (op_name == "make-series") return std::make_unique(); - else if (op_name == "mv-expand") + if (op_name == "mv-expand") return std::make_unique(); - else if (op_name == "print") + if (op_name == "print") return std::make_unique(); - else - return nullptr; + return nullptr; } bool ParserKQLQuery::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) diff --git a/src/Parsers/Kusto/parseKQLQuery.cpp b/src/Parsers/Kusto/parseKQLQuery.cpp index 34076168480..6caab3dce86 100644 --- a/src/Parsers/Kusto/parseKQLQuery.cpp +++ b/src/Parsers/Kusto/parseKQLQuery.cpp @@ -91,16 +91,14 @@ void writeQueryWithHighlightedErrorPositions( out << "\033[41;1m \033[0m"; return; } - else - { - size_t bytes_to_hilite = UTF8::seqLength(*current_position_to_hilite); - /// Bright on red background. - out << "\033[41;1m"; - out.write(current_position_to_hilite, bytes_to_hilite); - out << "\033[0m"; - pos = current_position_to_hilite + bytes_to_hilite; - } + size_t bytes_to_hilite = UTF8::seqLength(*current_position_to_hilite); + + /// Bright on red background. + out << "\033[41;1m"; + out.write(current_position_to_hilite, bytes_to_hilite); + out << "\033[0m"; + pos = current_position_to_hilite + bytes_to_hilite; } out.write(pos, end - pos); } @@ -289,8 +287,7 @@ UnmatchedParentheses checkKQLUnmatchedParentheses(TokenIterator begin) stack.push_back(*it); return stack; } - else if ( - (stack.back().type == TokenType::OpeningRoundBracket && it->type == TokenType::ClosingRoundBracket) + if ((stack.back().type == TokenType::OpeningRoundBracket && it->type == TokenType::ClosingRoundBracket) || (stack.back().type == TokenType::OpeningSquareBracket && it->type == TokenType::ClosingSquareBracket)) { /// Valid match. diff --git a/src/Parsers/Lexer.cpp b/src/Parsers/Lexer.cpp index 43c4ab867d1..bc25f80bee6 100644 --- a/src/Parsers/Lexer.cpp +++ b/src/Parsers/Lexer.cpp @@ -341,34 +341,32 @@ Token Lexer::nextTokenImpl() ++pos; return comment_until_end_of_line(); } - else + + ++pos; + + /// Nested multiline comments are supported according to the SQL standard. + size_t nesting_level = 1; + + while (pos + 2 <= end) { - ++pos; - - /// Nested multiline comments are supported according to the SQL standard. - size_t nesting_level = 1; - - while (pos + 2 <= end) + if (pos[0] == '/' && pos[1] == '*') { - if (pos[0] == '/' && pos[1] == '*') - { - pos += 2; - ++nesting_level; - } - else if (pos[0] == '*' && pos[1] == '/') - { - pos += 2; - --nesting_level; - - if (nesting_level == 0) - return Token(TokenType::Comment, token_begin, pos); - } - else - ++pos; + pos += 2; + ++nesting_level; } - pos = end; - return Token(TokenType::ErrorMultilineCommentIsNotClosed, token_begin, pos); + else if (pos[0] == '*' && pos[1] == '/') + { + pos += 2; + --nesting_level; + + if (nesting_level == 0) + return Token(TokenType::Comment, token_begin, pos); + } + else + ++pos; } + pos = end; + return Token(TokenType::ErrorMultilineCommentIsNotClosed, token_begin, pos); } return Token(TokenType::Slash, token_begin, pos); } @@ -515,15 +513,12 @@ Token Lexer::nextTokenImpl() ++pos; return Token(TokenType::BareWord, token_begin, pos); } - else - { - /// We will also skip unicode whitespaces in UTF-8 to support for queries copy-pasted from MS Word and similar. - pos = skipWhitespacesUTF8(pos, end); - if (pos > token_begin) - return Token(TokenType::Whitespace, token_begin, pos); - else - return Token(TokenType::Error, token_begin, ++pos); - } + + /// We will also skip unicode whitespaces in UTF-8 to support for queries copy-pasted from MS Word and similar. + pos = skipWhitespacesUTF8(pos, end); + if (pos > token_begin) + return Token(TokenType::Whitespace, token_begin, pos); + return Token(TokenType::Error, token_begin, ++pos); } } diff --git a/src/Parsers/MySQL/ASTAlterCommand.cpp b/src/Parsers/MySQL/ASTAlterCommand.cpp index 733cb657efc..2c7f3d63c30 100644 --- a/src/Parsers/MySQL/ASTAlterCommand.cpp +++ b/src/Parsers/MySQL/ASTAlterCommand.cpp @@ -377,18 +377,17 @@ bool ParserAlterCommand::parseImpl(IParser::Pos & pos, ASTPtr & node, Expected & if (k_add.ignore(pos, expected)) return parseAddCommand(pos, node, expected); - else if (k_drop.ignore(pos, expected)) + if (k_drop.ignore(pos, expected)) return parseDropCommand(pos, node, expected); - else if (k_alter.ignore(pos, expected)) + if (k_alter.ignore(pos, expected)) return parseAlterCommand(pos, node, expected); - else if (k_rename.ignore(pos, expected)) + if (k_rename.ignore(pos, expected)) return parseRenameCommand(pos, node, expected); - else if (k_modify.ignore(pos, expected)) + if (k_modify.ignore(pos, expected)) return parseModifyCommand(pos, node, expected); - else if (k_change.ignore(pos, expected)) + if (k_change.ignore(pos, expected)) return parseModifyCommand(pos, node, expected, true); - else - return parseOtherCommand(pos, node, expected); + return parseOtherCommand(pos, node, expected); } } diff --git a/src/Parsers/MySQL/ASTDeclareOption.cpp b/src/Parsers/MySQL/ASTDeclareOption.cpp index f4be38f4f2d..21d73fd901a 100644 --- a/src/Parsers/MySQL/ASTDeclareOption.cpp +++ b/src/Parsers/MySQL/ASTDeclareOption.cpp @@ -102,16 +102,15 @@ bool ParserCharsetOrCollateName::parseImpl(IParser::Pos & pos, ASTPtr & node, Ex if (p_identifier.parse(pos, node, expected)) return true; - else + + if (p_string_literal.parse(pos, node, expected)) { - if (p_string_literal.parse(pos, node, expected)) - { - const auto & string_value = node->as()->value.safeGet(); - node = std::make_shared(string_value); - return true; - } + const auto & string_value = node->as()->value.safeGet(); + node = std::make_shared(string_value); + return true; } + return false; } diff --git a/src/Parsers/ParserCreateQuery.cpp b/src/Parsers/ParserCreateQuery.cpp index 1faaaaafb3a..76d399558be 100644 --- a/src/Parsers/ParserCreateQuery.cpp +++ b/src/Parsers/ParserCreateQuery.cpp @@ -541,8 +541,7 @@ bool ParserStorage::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) storage_like = true; continue; } - else - return false; + return false; } if (!primary_key && s_primary_key.ignore(pos, expected)) @@ -552,8 +551,7 @@ bool ParserStorage::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) storage_like = true; continue; } - else - return false; + return false; } if (!order_by && s_order_by.ignore(pos, expected)) @@ -563,8 +561,7 @@ bool ParserStorage::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) storage_like = true; continue; } - else - return false; + return false; } if (!sample_by && s_sample_by.ignore(pos, expected)) @@ -574,8 +571,7 @@ bool ParserStorage::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) storage_like = true; continue; } - else - return false; + return false; } if (!ttl_table && s_ttl.ignore(pos, expected)) @@ -585,8 +581,7 @@ bool ParserStorage::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) storage_like = true; continue; } - else - return false; + return false; } /// Do not allow SETTINGS clause without ENGINE, @@ -1279,40 +1274,35 @@ bool ParserTableOverrideDeclaration::parseImpl(Pos & pos, ASTPtr & node, Expecte { if (expression_p.parse(pos, partition_by, expected)) continue; - else - return false; + return false; } if (!primary_key && s_primary_key.ignore(pos, expected)) { if (expression_p.parse(pos, primary_key, expected)) continue; - else - return false; + return false; } if (!order_by && s_order_by.ignore(pos, expected)) { if (expression_p.parse(pos, order_by, expected)) continue; - else - return false; + return false; } if (!sample_by && s_sample_by.ignore(pos, expected)) { if (expression_p.parse(pos, sample_by, expected)) continue; - else - return false; + return false; } if (!ttl_table && s_ttl.ignore(pos, expected)) { if (parser_ttl_list.parse(pos, ttl_table, expected)) continue; - else - return false; + return false; } break; diff --git a/src/Parsers/ParserDropQuery.cpp b/src/Parsers/ParserDropQuery.cpp index 38ebca83dae..6e8654a5642 100644 --- a/src/Parsers/ParserDropQuery.cpp +++ b/src/Parsers/ParserDropQuery.cpp @@ -150,12 +150,11 @@ bool ParserDropQuery::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) if (s_drop.ignore(pos, expected)) return parseDropQuery(pos, node, expected, ASTDropQuery::Kind::Drop); - else if (s_detach.ignore(pos, expected)) + if (s_detach.ignore(pos, expected)) return parseDropQuery(pos, node, expected, ASTDropQuery::Kind::Detach); - else if (s_truncate.ignore(pos, expected)) + if (s_truncate.ignore(pos, expected)) return parseDropQuery(pos, node, expected, ASTDropQuery::Kind::Truncate); - else - return false; + return false; } } diff --git a/src/Parsers/ParserRenameQuery.cpp b/src/Parsers/ParserRenameQuery.cpp index e07fd7d492e..6921c8d6422 100644 --- a/src/Parsers/ParserRenameQuery.cpp +++ b/src/Parsers/ParserRenameQuery.cpp @@ -56,7 +56,7 @@ bool ParserRenameQuery::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) node = query; return true; } - else if (s_rename_table.ignore(pos, expected)) + if (s_rename_table.ignore(pos, expected)) ; else if (s_exchange_tables.ignore(pos, expected)) exchange = true; diff --git a/src/Parsers/ParserSetQuery.cpp b/src/Parsers/ParserSetQuery.cpp index f08d2b978c6..cb9ba5909f7 100644 --- a/src/Parsers/ParserSetQuery.cpp +++ b/src/Parsers/ParserSetQuery.cpp @@ -218,7 +218,7 @@ bool ParserSetQuery::parseNameValuePair(SettingChange & change, IParser::Pos & p return true; } - else if (!literal_or_map_p.parse(pos, value, expected)) + if (!literal_or_map_p.parse(pos, value, expected)) return false; tryGetIdentifierNameInto(name, change.name); @@ -279,7 +279,7 @@ bool ParserSetQuery::parseNameValuePairWithParameterOrDefault( return true; } - else if (!value_p.parse(pos, node, expected)) + if (!value_p.parse(pos, node, expected)) return false; change.name = name; diff --git a/src/Parsers/ParserUndropQuery.cpp b/src/Parsers/ParserUndropQuery.cpp index 57da47df70d..c0c9bffe0cb 100644 --- a/src/Parsers/ParserUndropQuery.cpp +++ b/src/Parsers/ParserUndropQuery.cpp @@ -74,8 +74,7 @@ bool ParserUndropQuery::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) if (s_undrop.ignore(pos, expected)) return parseUndropQuery(pos, node, expected); - else - return false; + return false; } } diff --git a/src/Parsers/TokenIterator.cpp b/src/Parsers/TokenIterator.cpp index 08877e0b2fe..714ce9b52e1 100644 --- a/src/Parsers/TokenIterator.cpp +++ b/src/Parsers/TokenIterator.cpp @@ -25,7 +25,7 @@ UnmatchedParentheses checkUnmatchedParentheses(TokenIterator begin) stack.push_back(*it); return stack; } - else if ((stack.back().type == TokenType::OpeningRoundBracket && it->type == TokenType::ClosingRoundBracket) + if ((stack.back().type == TokenType::OpeningRoundBracket && it->type == TokenType::ClosingRoundBracket) || (stack.back().type == TokenType::OpeningSquareBracket && it->type == TokenType::ClosingSquareBracket)) { /// Valid match. diff --git a/src/Parsers/parseDatabaseAndTableName.cpp b/src/Parsers/parseDatabaseAndTableName.cpp index ff0d9d7cd84..144f3901add 100644 --- a/src/Parsers/parseDatabaseAndTableName.cpp +++ b/src/Parsers/parseDatabaseAndTableName.cpp @@ -110,7 +110,7 @@ bool parseDatabaseAndTableNameOrAsterisks(IParser::Pos & pos, Expected & expecte table.clear(); return true; } - else if (identifier_parser.parse(pos, ast, expected)) + if (identifier_parser.parse(pos, ast, expected)) { /// db.table database = std::move(first_identifier); diff --git a/src/Parsers/parseQuery.cpp b/src/Parsers/parseQuery.cpp index fab5dac8f87..498d8a0f4e9 100644 --- a/src/Parsers/parseQuery.cpp +++ b/src/Parsers/parseQuery.cpp @@ -91,16 +91,14 @@ void writeQueryWithHighlightedErrorPositions( out << "\033[41;1m \033[0m"; return; } - else - { - ssize_t bytes_to_hilite = std::min(UTF8::seqLength(*current_position_to_hilite), end - current_position_to_hilite); - /// Bright on red background. - out << "\033[41;1m"; - out.write(current_position_to_hilite, bytes_to_hilite); - out << "\033[0m"; - pos = current_position_to_hilite + bytes_to_hilite; - } + ssize_t bytes_to_hilite = std::min(UTF8::seqLength(*current_position_to_hilite), end - current_position_to_hilite); + + /// Bright on red background. + out << "\033[41;1m"; + out.write(current_position_to_hilite, bytes_to_hilite); + out << "\033[0m"; + pos = current_position_to_hilite + bytes_to_hilite; } out.write(pos, end - pos); } diff --git a/src/Parsers/queryNormalization.cpp b/src/Parsers/queryNormalization.cpp index 4890ad6952d..9cdfecafd8e 100644 --- a/src/Parsers/queryNormalization.cpp +++ b/src/Parsers/queryNormalization.cpp @@ -32,7 +32,7 @@ UInt64 normalizedQueryHash(const char * begin, const char * end, bool keep_names prev_comma = false; continue; } - else if (token.type == TokenType::Comma) + if (token.type == TokenType::Comma) { if (num_literals_in_sequence) { @@ -159,7 +159,7 @@ void normalizeQueryToPODArray(const char * begin, const char * end, PaddedPODArr prev_comma = false; continue; } - else if (token.type == TokenType::Comma) + if (token.type == TokenType::Comma) { if (num_literals_in_sequence) { diff --git a/src/Planner/Planner.cpp b/src/Planner/Planner.cpp index ee74ed45db5..44dca952a10 100644 --- a/src/Planner/Planner.cpp +++ b/src/Planner/Planner.cpp @@ -1497,14 +1497,12 @@ void Planner::buildPlanForQueryNode() { if (settings[Setting::allow_experimental_parallel_reading_from_replicas] >= 2) throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "FINAL modifier is not supported with parallel replicas"); - else - { - LOG_DEBUG( - getLogger("Planner"), - "FINAL modifier is not supported with parallel replicas. Query will be executed without using them."); - auto & mutable_context = planner_context->getMutableQueryContext(); - mutable_context->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0)); - } + + LOG_DEBUG( + getLogger("Planner"), + "FINAL modifier is not supported with parallel replicas. Query will be executed without using them."); + auto & mutable_context = planner_context->getMutableQueryContext(); + mutable_context->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0)); } } } @@ -1516,16 +1514,12 @@ void Planner::buildPlanForQueryNode() { if (settings[Setting::allow_experimental_parallel_reading_from_replicas] >= 2) throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "JOINs are not supported with parallel replicas"); - else - { - LOG_DEBUG( - getLogger("Planner"), - "JOINs are not supported with parallel replicas. Query will be executed without using them."); - auto & mutable_context = planner_context->getMutableQueryContext(); - mutable_context->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0)); - mutable_context->setSetting("parallel_replicas_custom_key", String{""}); - } + LOG_DEBUG(getLogger("Planner"), "JOINs are not supported with parallel replicas. Query will be executed without using them."); + + auto & mutable_context = planner_context->getMutableQueryContext(); + mutable_context->setSetting("allow_experimental_parallel_reading_from_replicas", Field(0)); + mutable_context->setSetting("parallel_replicas_custom_key", String{""}); } } diff --git a/src/Planner/PlannerActionsVisitor.cpp b/src/Planner/PlannerActionsVisitor.cpp index 80139a713ff..abf1f759719 100644 --- a/src/Planner/PlannerActionsVisitor.cpp +++ b/src/Planner/PlannerActionsVisitor.cpp @@ -619,9 +619,9 @@ PlannerActionsVisitorImpl::NodeNameAndNodeMinLevel PlannerActionsVisitorImpl::vi if (node_type == QueryTreeNodeType::COLUMN) return visitColumn(node); - else if (node_type == QueryTreeNodeType::CONSTANT) + if (node_type == QueryTreeNodeType::CONSTANT) return visitConstant(node); - else if (node_type == QueryTreeNodeType::FUNCTION) + if (node_type == QueryTreeNodeType::FUNCTION) return visitFunction(node); throw Exception(ErrorCodes::UNSUPPORTED_METHOD, @@ -690,19 +690,15 @@ PlannerActionsVisitorImpl::NodeNameAndNodeMinLevel PlannerActionsVisitorImpl::vi { return calculateActionNodeNameWithCastIfNeeded(constant_node); } - else + + // Need to check if constant folded from QueryNode until https://github.com/ClickHouse/ClickHouse/issues/60847 is fixed. + if (constant_node.hasSourceExpression() && constant_node.getSourceExpression()->getNodeType() != QueryTreeNodeType::QUERY) { - // Need to check if constant folded from QueryNode until https://github.com/ClickHouse/ClickHouse/issues/60847 is fixed. - if (constant_node.hasSourceExpression() && constant_node.getSourceExpression()->getNodeType() != QueryTreeNodeType::QUERY) - { - if (constant_node.receivedFromInitiatorServer()) - return calculateActionNodeNameWithCastIfNeeded(constant_node); - else - return action_node_name_helper.calculateActionNodeName(constant_node.getSourceExpression()); - } - else - return calculateConstantActionNodeName(constant_literal, constant_type); + if (constant_node.receivedFromInitiatorServer()) + return calculateActionNodeNameWithCastIfNeeded(constant_node); + return action_node_name_helper.calculateActionNodeName(constant_node.getSourceExpression()); } + return calculateConstantActionNodeName(constant_literal, constant_type); }(); ColumnWithTypeAndName column; diff --git a/src/Planner/PlannerJoinTree.cpp b/src/Planner/PlannerJoinTree.cpp index 8691f454ef8..805745fe5f9 100644 --- a/src/Planner/PlannerJoinTree.cpp +++ b/src/Planner/PlannerJoinTree.cpp @@ -290,9 +290,10 @@ bool applyTrivialCountIfPossible( (table_node->getTableExpressionModifiers()->hasFinal() || table_node->getTableExpressionModifiers()->hasSampleSizeRatio() || table_node->getTableExpressionModifiers()->hasSampleOffsetRatio())) return false; - else if (table_function_node && table_function_node->getTableExpressionModifiers().has_value() && - (table_function_node->getTableExpressionModifiers()->hasFinal() || table_function_node->getTableExpressionModifiers()->hasSampleSizeRatio() || - table_function_node->getTableExpressionModifiers()->hasSampleOffsetRatio())) + if (table_function_node && table_function_node->getTableExpressionModifiers().has_value() + && (table_function_node->getTableExpressionModifiers()->hasFinal() + || table_function_node->getTableExpressionModifiers()->hasSampleSizeRatio() + || table_function_node->getTableExpressionModifiers()->hasSampleOffsetRatio())) return false; // TODO: It's possible to optimize count() given only partition predicates diff --git a/src/Planner/PlannerJoins.cpp b/src/Planner/PlannerJoins.cpp index 8857fda5b4c..be75e3273f6 100644 --- a/src/Planner/PlannerJoins.cpp +++ b/src/Planner/PlannerJoins.cpp @@ -261,21 +261,19 @@ void buildJoinClause( "JOIN {} ON expression expected non-empty left and right table expressions", join_node.formatASTForErrorMessage()); } - else if (left_expression_sides.size() == 1 && right_expression_sides.empty()) + if (left_expression_sides.size() == 1 && right_expression_sides.empty()) { auto expression_side = *left_expression_sides.begin(); - auto & dag = expression_side == JoinTableSide::Left ? left_dag : right_dag; + auto & dag = expression_side == JoinTableSide::Left ? left_dag : right_dag; const auto * node = appendExpression(dag, join_expression, planner_context, join_node); join_clause.addCondition(expression_side, node); - } else if (left_expression_sides.empty() && right_expression_sides.size() == 1) { auto expression_side = *right_expression_sides.begin(); - auto & dag = expression_side == JoinTableSide::Left ? left_dag : right_dag; + auto & dag = expression_side == JoinTableSide::Left ? left_dag : right_dag; const auto * node = appendExpression(dag, join_expression, planner_context, join_node); join_clause.addCondition(expression_side, node); - } else if (left_expression_sides.size() == 1 && right_expression_sides.size() == 1) { @@ -301,7 +299,8 @@ void buildJoinClause( { if (join_clause.hasASOF()) { - throw Exception(ErrorCodes::INVALID_JOIN_ON_EXPRESSION, + throw Exception( + ErrorCodes::INVALID_JOIN_ON_EXPRESSION, "JOIN {} ASOF JOIN expects exactly one inequality in ON section", join_node.formatASTForErrorMessage()); } @@ -337,11 +336,11 @@ void buildJoinClause( { throw Exception( ErrorCodes::INVALID_JOIN_ON_EXPRESSION, - "JOIN {} join expression contains column from left and right table, you may try experimental support of this feature by `SET allow_experimental_join_condition = 1`", + "JOIN {} join expression contains column from left and right table, you may try experimental support of this feature " + "by `SET allow_experimental_join_condition = 1`", join_node.formatASTForErrorMessage()); } } - } else { diff --git a/src/Planner/PlannerWindowFunctions.cpp b/src/Planner/PlannerWindowFunctions.cpp index ce27c4ae86e..29c190b45ad 100644 --- a/src/Planner/PlannerWindowFunctions.cpp +++ b/src/Planner/PlannerWindowFunctions.cpp @@ -148,15 +148,15 @@ void sortWindowDescriptions(std::vector & window_descriptions { if (left[i].column_name < right[i].column_name) return true; - else if (left[i].column_name > right[i].column_name) + if (left[i].column_name > right[i].column_name) return false; - else if (left[i].direction < right[i].direction) + if (left[i].direction < right[i].direction) return true; - else if (left[i].direction > right[i].direction) + if (left[i].direction > right[i].direction) return false; - else if (left[i].nulls_direction < right[i].nulls_direction) + if (left[i].nulls_direction < right[i].nulls_direction) return true; - else if (left[i].nulls_direction > right[i].nulls_direction) + if (left[i].nulls_direction > right[i].nulls_direction) return false; assert(left[i] == right[i]); diff --git a/src/Planner/Utils.cpp b/src/Planner/Utils.cpp index 665cf5cadba..e825de2719b 100644 --- a/src/Planner/Utils.cpp +++ b/src/Planner/Utils.cpp @@ -146,7 +146,7 @@ ASTPtr queryNodeToSelectQuery(const QueryTreeNodePtr & query_node) { if (auto * /*select_query*/ _ = result_ast->as()) break; - else if (auto * select_with_union = result_ast->as()) + if (auto * select_with_union = result_ast->as()) result_ast = select_with_union->list_of_selects->children.at(0); else if (auto * subquery = result_ast->as()) result_ast = subquery->children.at(0); diff --git a/src/Processors/Executors/PipelineExecutor.cpp b/src/Processors/Executors/PipelineExecutor.cpp index d02599c4d17..e8e1d5a941b 100644 --- a/src/Processors/Executors/PipelineExecutor.cpp +++ b/src/Processors/Executors/PipelineExecutor.cpp @@ -222,7 +222,7 @@ void PipelineExecutor::finalizeExecution() all_processors_finished = false; break; } - else if (node->processor && read_progress_callback) + if (node->processor && read_progress_callback) { /// Some executors might have reported progress as part of their finish() call /// For example, when reading from parallel replicas the coordinator will cancel the queries as soon as it diff --git a/src/Processors/Formats/ISchemaReader.cpp b/src/Processors/Formats/ISchemaReader.cpp index e002e64b7e5..f169c39dbc4 100644 --- a/src/Processors/Formats/ISchemaReader.cpp +++ b/src/Processors/Formats/ISchemaReader.cpp @@ -40,15 +40,14 @@ void checkFinalInferredType( "of the settings allow_experimental_object_type/input_format_json_read_objects_as_strings", name, rows_read); - else - throw Exception( - ErrorCodes::ONLY_NULLS_WHILE_READING_SCHEMA, - "Cannot determine type for column '{}' by first {} rows " - "of data, most likely this column contains only Nulls or empty Arrays/Maps. " - "Column types from setting schema_inference_hints couldn't be parsed because of error: {}", - name, - rows_read, - hints_parsing_error); + throw Exception( + ErrorCodes::ONLY_NULLS_WHILE_READING_SCHEMA, + "Cannot determine type for column '{}' by first {} rows " + "of data, most likely this column contains only Nulls or empty Arrays/Maps. " + "Column types from setting schema_inference_hints couldn't be parsed because of error: {}", + name, + rows_read, + hints_parsing_error); } type = default_type; diff --git a/src/Processors/Formats/ISchemaReader.h b/src/Processors/Formats/ISchemaReader.h index 23c6606a6bd..0fa418ba3ab 100644 --- a/src/Processors/Formats/ISchemaReader.h +++ b/src/Processors/Formats/ISchemaReader.h @@ -189,16 +189,15 @@ void chooseResultColumnType( column_name, row, type->getName()); - else - throw Exception( - ErrorCodes::TYPE_MISMATCH, - "Automatically defined type {} for column '{}' in row {} differs from type defined by previous rows: {}. " - "Column types from setting schema_inference_hints couldn't be parsed because of error: {}", - new_type->getName(), - column_name, - row, - type->getName(), - hints_parsing_error); + throw Exception( + ErrorCodes::TYPE_MISMATCH, + "Automatically defined type {} for column '{}' in row {} differs from type defined by previous rows: {}. " + "Column types from setting schema_inference_hints couldn't be parsed because of error: {}", + new_type->getName(), + column_name, + row, + type->getName(), + hints_parsing_error); } } diff --git a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp index c9ca9efabee..90ddee2e2b4 100644 --- a/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp +++ b/src/Processors/Formats/Impl/ArrowColumnToCHColumn.cpp @@ -426,9 +426,9 @@ static ColumnWithTypeAndName readColumnWithDecimalData(const std::shared_ptr(precision, arrow_decimal_type->scale()); if (precision <= DecimalUtils::max_precision) return readColumnWithDecimalDataImpl(arrow_column, column_name, internal_type); - else if (precision <= DecimalUtils::max_precision) + if (precision <= DecimalUtils::max_precision) return readColumnWithDecimalDataImpl(arrow_column, column_name, internal_type); - else if (precision <= DecimalUtils::max_precision) + if (precision <= DecimalUtils::max_precision) return readColumnWithDecimalDataImpl(arrow_column, column_name, internal_type); return readColumnWithDecimalDataImpl(arrow_column, column_name, internal_type); } @@ -1328,16 +1328,14 @@ Chunk ArrowColumnToCHColumn::arrowColumnsToCHChunk(const NameToArrowColumn & nam { if (!allow_missing_columns) throw Exception{ErrorCodes::THERE_IS_NO_COLUMN, "Column '{}' is not presented in input data.", header_column.name}; - else - { - column.name = header_column.name; - column.type = header_column.type; - column.column = header_column.column->cloneResized(num_rows); - columns.push_back(std::move(column.column)); - if (block_missing_values) - block_missing_values->setBits(column_i, num_rows); - continue; - } + + column.name = header_column.name; + column.type = header_column.type; + column.column = header_column.column->cloneResized(num_rows); + columns.push_back(std::move(column.column)); + if (block_missing_values) + block_missing_values->setBits(column_i, num_rows); + continue; } } else diff --git a/src/Processors/Formats/Impl/AvroRowInputFormat.cpp b/src/Processors/Formats/Impl/AvroRowInputFormat.cpp index 2ed55cca30c..2d32214dba0 100644 --- a/src/Processors/Formats/Impl/AvroRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/AvroRowInputFormat.cpp @@ -192,7 +192,7 @@ static AvroDeserializer::DeserializeFn createDecimalDeserializeFn(const avro::No target_type->getName(), field_type_size, tmp.size()); - else if (tmp.size() != field_type_size) + if (tmp.size() != field_type_size) { /// Extent value to required size by adding padding. /// Check if value is negative or positive. @@ -224,8 +224,7 @@ static std::string nodeName(avro::NodePtr node) { if (node->hasName()) return node->name().simpleName(); - else - return avro::toString(node->type()); + return avro::toString(node->type()); } static bool canBeDeserializedFromFixed(const DataTypePtr & target_type, size_t fixed_size) @@ -389,8 +388,7 @@ AvroDeserializer::DeserializeFn AvroDeserializer::createDeserializeFn(const avro }; } /// FIXME Support UNION has more than two datatypes. - else if ( - root_node->leaves() == 2 + if (root_node->leaves() == 2 && (root_node->leafAt(0)->type() == avro::AVRO_NULL || root_node->leafAt(1)->type() == avro::AVRO_NULL)) { int non_null_union_index = root_node->leafAt(0)->type() == avro::AVRO_NULL ? 1 : 0; @@ -413,7 +411,7 @@ AvroDeserializer::DeserializeFn AvroDeserializer::createDeserializeFn(const avro return true; }; } - else if (null_as_default) + if (null_as_default) { auto nested_deserialize = createDeserializeFn(root_node->leafAt(non_null_union_index), target_type); return [non_null_union_index, nested_deserialize](IColumn & column, avro::Decoder & decoder) @@ -428,15 +426,13 @@ AvroDeserializer::DeserializeFn AvroDeserializer::createDeserializeFn(const avro return false; }; } - else - { - throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "Cannot insert Avro Union(Null, {}) into non-nullable type {}. To use default value on NULL, enable setting " - "input_format_null_as_default", - avro::toString(root_node->leafAt(non_null_union_index)->type()), - target_type->getName()); - } + + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Cannot insert Avro Union(Null, {}) into non-nullable type {}. To use default value on NULL, enable setting " + "input_format_null_as_default", + avro::toString(root_node->leafAt(non_null_union_index)->type()), + target_type->getName()); } break; } @@ -452,16 +448,14 @@ AvroDeserializer::DeserializeFn AvroDeserializer::createDeserializeFn(const avro return true; }; } - else + + return [](IColumn & column, avro::Decoder & decoder) { - return [](IColumn & column, avro::Decoder & decoder) - { - ColumnNullable & col = assert_cast(column); - decoder.decodeNull(); - col.insertDefault(); - return true; - }; - } + ColumnNullable & col = assert_cast(column); + decoder.decodeNull(); + col.insertDefault(); + return true; + }; } else if (null_as_default) { @@ -798,8 +792,7 @@ AvroDeserializer::Action AvroDeserializer::createAction(const Block & header, co auto resolved_node = avro::resolveSymbol(node); if (keep_going) return createAction(header, resolved_node, current_path); - else - return AvroDeserializer::Action(createSkipFn(resolved_node)); + return AvroDeserializer::Action(createSkipFn(resolved_node)); } if (header.has(current_path)) @@ -1089,8 +1082,7 @@ static uint32_t readConfluentSchemaId(ReadBuffer & in) /* empty or incomplete message without Avro Confluent magic number or schema id */ throw Exception(ErrorCodes::INCORRECT_DATA, "Missing AvroConfluent magic byte or schema identifier."); } - else - throw; + throw; } if (magic != 0x00) @@ -1232,7 +1224,7 @@ DataTypePtr AvroSchemaReader::avroNodeToDataType(avro::NodePtr node) values.emplace_back(node->nameAt(i), i); return std::make_shared(std::move(values)); } - else if (node->names() < 32768) + if (node->names() < 32768) { EnumValues::Values values; for (int i = 0; i != static_cast(node->names()); ++i) diff --git a/src/Processors/Formats/Impl/AvroRowOutputFormat.cpp b/src/Processors/Formats/Impl/AvroRowOutputFormat.cpp index a79a7d10c78..71ed4f83486 100644 --- a/src/Processors/Formats/Impl/AvroRowOutputFormat.cpp +++ b/src/Processors/Formats/Impl/AvroRowOutputFormat.cpp @@ -368,12 +368,13 @@ AvroSerializer::SchemaWithSerializeFn AvroSerializer::createSchemaWithSerializeF { return nested_mapping; } - else - { - avro::UnionSchema union_schema; - union_schema.addType(avro::NullSchema()); - union_schema.addType(nested_mapping.schema); - return {union_schema, [nested_mapping](const IColumn & column, size_t row_num, avro::Encoder & encoder) + + avro::UnionSchema union_schema; + union_schema.addType(avro::NullSchema()); + union_schema.addType(nested_mapping.schema); + return { + union_schema, + [nested_mapping](const IColumn & column, size_t row_num, avro::Encoder & encoder) { const ColumnNullable & col = assert_cast(column); if (!col.isNullAt(row_num)) @@ -387,7 +388,6 @@ AvroSerializer::SchemaWithSerializeFn AvroSerializer::createSchemaWithSerializeF encoder.encodeNull(); } }}; - } } case TypeIndex::LowCardinality: { diff --git a/src/Processors/Formats/Impl/BSONEachRowRowInputFormat.cpp b/src/Processors/Formats/Impl/BSONEachRowRowInputFormat.cpp index 6a3475a1830..408bbbcbde3 100644 --- a/src/Processors/Formats/Impl/BSONEachRowRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/BSONEachRowRowInputFormat.cpp @@ -71,20 +71,17 @@ inline size_t BSONEachRowRowInputFormat::columnIndex(const StringRef & name, siz { return prev_positions[key_index]->second; } - else + + const auto it = name_map.find(name); + + if (it != name_map.end()) { - const auto it = name_map.find(name); + if (key_index < prev_positions.size()) + prev_positions[key_index] = it; - if (it != name_map.end()) - { - if (key_index < prev_positions.size()) - prev_positions[key_index] = it; - - return it->second; - } - else - return UNKNOWN_FIELD; + return it->second; } + return UNKNOWN_FIELD; } /// Read the field name. Resulting StringRef is valid only before next read from buf. @@ -825,8 +822,7 @@ bool BSONEachRowRowInputFormat::readRow(MutableColumns & columns, RowReadExtensi const auto & type = header.getByPosition(i).type; if (format_settings.force_null_for_omitted_fields && !isNullableOrLowCardinalityNullable(type)) throw Exception(ErrorCodes::TYPE_MISMATCH, "Cannot insert NULL value into a column of type '{}' at index {}", type->getName(), i); - else - type->insertDefaultInto(*columns[i]); + type->insertDefaultInto(*columns[i]); } if (format_settings.defaults_for_omitted_fields) diff --git a/src/Processors/Formats/Impl/CSVRowInputFormat.cpp b/src/Processors/Formats/Impl/CSVRowInputFormat.cpp index cf58a4057c8..c89268d98fb 100644 --- a/src/Processors/Formats/Impl/CSVRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/CSVRowInputFormat.cpp @@ -130,9 +130,9 @@ void CSVFormatReader::skipRow() if (pos > istr.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (pos == istr.buffer().end()) + if (pos == istr.buffer().end()) continue; - else if (*pos == '"') + if (*pos == '"') { ++istr.position(); if (!istr.eof() && *istr.position() == '"') @@ -148,7 +148,7 @@ void CSVFormatReader::skipRow() if (pos > istr.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (pos == istr.buffer().end()) + if (pos == istr.buffer().end()) continue; if (*pos == '"') @@ -165,12 +165,12 @@ void CSVFormatReader::skipRow() ++istr.position(); return; } - else if (*pos == '\r') + if (*pos == '\r') { ++istr.position(); if (format_settings.csv.allow_cr_end_of_line) return; - else if (!istr.eof() && *pos == '\n') + if (!istr.eof() && *pos == '\n') { ++pos; return; @@ -529,9 +529,9 @@ std::pair fileSegmentationEngineCSVImpl(ReadBuffer & in, DB::Memor pos = find_first_symbols<'"'>(pos, in.buffer().end()); if (pos > in.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (pos == in.buffer().end()) + if (pos == in.buffer().end()) continue; - else if (*pos == '"') + if (*pos == '"') { ++pos; if (loadAtPosition(in, memory, pos) && *pos == '"') @@ -545,7 +545,7 @@ std::pair fileSegmentationEngineCSVImpl(ReadBuffer & in, DB::Memor pos = find_first_symbols<'"', '\r', '\n'>(pos, in.buffer().end()); if (pos > in.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (pos == in.buffer().end()) + if (pos == in.buffer().end()) continue; if (*pos == '"') @@ -566,7 +566,7 @@ std::pair fileSegmentationEngineCSVImpl(ReadBuffer & in, DB::Memor ++pos; if (settings.csv.allow_cr_end_of_line) continue; - else if (loadAtPosition(in, memory, pos) && *pos == '\n') + if (loadAtPosition(in, memory, pos) && *pos == '\n') ++pos; else continue; diff --git a/src/Processors/Formats/Impl/ConstantExpressionTemplate.cpp b/src/Processors/Formats/Impl/ConstantExpressionTemplate.cpp index 13eb6d3403f..6d4b8d4ccda 100644 --- a/src/Processors/Formats/Impl/ConstantExpressionTemplate.cpp +++ b/src/Processors/Formats/Impl/ConstantExpressionTemplate.cpp @@ -588,64 +588,62 @@ bool ConstantExpressionTemplate::parseLiteralAndAssertType( columns[column_idx]->insert(array_same_types); return true; } + + Field number; + if (type_info.is_nullable && 4 <= istr.available() && 0 == strncasecmp(istr.position(), "NULL", 4)) + { + istr.position() += 4; + } else { - Field number; - if (type_info.is_nullable && 4 <= istr.available() && 0 == strncasecmp(istr.position(), "NULL", 4)) + /// ParserNumber::parse(...) is about 20x slower than strtod(...) + /// because of using ASTPtr, Expected and Tokens, which are not needed here. + /// Parse numeric literal in the same way, as ParserNumber does, but use strtod and strtoull directly. + bool negative = *istr.position() == '-'; + if (negative || *istr.position() == '+') + ++istr.position(); + + static constexpr size_t MAX_LENGTH_OF_NUMBER = 319; + char buf[MAX_LENGTH_OF_NUMBER + 1]; + size_t bytes_to_copy = std::min(istr.available(), MAX_LENGTH_OF_NUMBER); + memcpy(buf, istr.position(), bytes_to_copy); + buf[bytes_to_copy] = 0; + + const bool hex_like = bytes_to_copy >= 2 && buf[0] == '0' && (buf[1] == 'x' || buf[1] == 'X'); + + char * pos_double = buf; + errno = 0; + Float64 float_value = std::strtod(buf, &pos_double); + if (pos_double == buf || errno == ERANGE || float_value < 0) + return false; + + if (negative) + float_value = -float_value; + + char * pos_integer = buf; + errno = 0; + UInt64 uint_value = std::strtoull(buf, &pos_integer, hex_like ? 16 : 10); + if (pos_integer == pos_double && errno != ERANGE && (!negative || uint_value <= (1ULL << 63))) { - istr.position() += 4; - } - else - { - /// ParserNumber::parse(...) is about 20x slower than strtod(...) - /// because of using ASTPtr, Expected and Tokens, which are not needed here. - /// Parse numeric literal in the same way, as ParserNumber does, but use strtod and strtoull directly. - bool negative = *istr.position() == '-'; - if (negative || *istr.position() == '+') - ++istr.position(); - - static constexpr size_t MAX_LENGTH_OF_NUMBER = 319; - char buf[MAX_LENGTH_OF_NUMBER + 1]; - size_t bytes_to_copy = std::min(istr.available(), MAX_LENGTH_OF_NUMBER); - memcpy(buf, istr.position(), bytes_to_copy); - buf[bytes_to_copy] = 0; - - const bool hex_like = bytes_to_copy >= 2 && buf[0] == '0' && (buf[1] == 'x' || buf[1] == 'X'); - - char * pos_double = buf; - errno = 0; - Float64 float_value = std::strtod(buf, &pos_double); - if (pos_double == buf || errno == ERANGE || float_value < 0) - return false; - - if (negative) - float_value = -float_value; - - char * pos_integer = buf; - errno = 0; - UInt64 uint_value = std::strtoull(buf, &pos_integer, hex_like ? 16 : 10); - if (pos_integer == pos_double && errno != ERANGE && (!negative || uint_value <= (1ULL << 63))) - { - istr.position() += pos_integer - buf; - if (negative && type_info.main_type == Type::Int64) - number = static_cast(-uint_value); - else if (type_info.main_type == Type::UInt64 && (!negative || uint_value == 0)) - number = uint_value; - else - return false; - } - else if (type_info.main_type == Type::Float64) - { - istr.position() += pos_double - buf; - number = float_value; - } + istr.position() += pos_integer - buf; + if (negative && type_info.main_type == Type::Int64) + number = static_cast(-uint_value); + else if (type_info.main_type == Type::UInt64 && (!negative || uint_value == 0)) + number = uint_value; else return false; } - - columns[column_idx]->insert(number); - return true; + else if (type_info.main_type == Type::Float64) + { + istr.position() += pos_double - buf; + number = float_value; + } + else + return false; } + + columns[column_idx]->insert(number); + return true; } ColumnPtr ConstantExpressionTemplate::evaluateAll(BlockMissingValues & nulls, size_t column_idx, const DataTypePtr & expected_type, size_t offset) diff --git a/src/Processors/Formats/Impl/JSONAsStringRowInputFormat.cpp b/src/Processors/Formats/Impl/JSONAsStringRowInputFormat.cpp index a0218c29f3a..1985c7433c8 100644 --- a/src/Processors/Formats/Impl/JSONAsStringRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/JSONAsStringRowInputFormat.cpp @@ -41,7 +41,7 @@ bool JSONAsRowInputFormat::readRow(MutableColumns & columns, RowReadExtension &) /// ';' means the end of query, but it cannot be before ']'. return allow_new_rows = false; } - else if (data_in_square_brackets && *in->position() == ']') + if (data_in_square_brackets && *in->position() == ']') { /// ']' means the end of query. return allow_new_rows = false; diff --git a/src/Processors/Formats/Impl/JSONEachRowRowInputFormat.cpp b/src/Processors/Formats/Impl/JSONEachRowRowInputFormat.cpp index 8855a1bc28d..77e75efd06f 100644 --- a/src/Processors/Formats/Impl/JSONEachRowRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/JSONEachRowRowInputFormat.cpp @@ -77,19 +77,16 @@ inline size_t JSONEachRowRowInputFormat::columnIndex(StringRef name, size_t key_ { return prev_positions[key_index]->second; } - else - { - const auto it = name_map.find(name); - if (it != name_map.end()) - { - if (key_index < prev_positions.size()) - prev_positions[key_index] = it; - return it->second; - } - else - return UNKNOWN_FIELD; + const auto it = name_map.find(name); + if (it != name_map.end()) + { + if (key_index < prev_positions.size()) + prev_positions[key_index] = it; + + return it->second; } + return UNKNOWN_FIELD; } /** Read the field name and convert it to column name @@ -145,7 +142,7 @@ inline bool JSONEachRowRowInputFormat::advanceToNextKey(size_t key_index) if (in->eof()) throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Unexpected end of stream while parsing JSONEachRow format"); - else if (*in->position() == '}') + if (*in->position() == '}') { ++in->position(); return false; @@ -238,8 +235,7 @@ bool JSONEachRowRowInputFormat::readRow(MutableColumns & columns, RowReadExtensi const auto & type = header.getByPosition(i).type; if (format_settings.force_null_for_omitted_fields && !isNullableOrLowCardinalityNullable(type)) throw Exception(ErrorCodes::TYPE_MISMATCH, "Cannot insert NULL value into a column `{}` of type '{}'", columnName(i), type->getName()); - else - type->insertDefaultInto(*columns[i]); + type->insertDefaultInto(*columns[i]); } diff --git a/src/Processors/Formats/Impl/JSONRowInputFormat.cpp b/src/Processors/Formats/Impl/JSONRowInputFormat.cpp index 615b85ab32c..aff18e298fa 100644 --- a/src/Processors/Formats/Impl/JSONRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/JSONRowInputFormat.cpp @@ -96,11 +96,9 @@ NamesAndTypesList JSONRowSchemaReader::readSchema() peekable_buf->rollbackToCheckpoint(true); return JSONEachRowSchemaReader::readSchema(); } - else - { - JSONUtils::skipObjectStart(*peekable_buf); - return JSONUtils::readMetadata(*peekable_buf, format_settings.json); - } + + JSONUtils::skipObjectStart(*peekable_buf); + return JSONUtils::readMetadata(*peekable_buf, format_settings.json); } void registerInputFormatJSON(FormatFactory & factory) diff --git a/src/Processors/Formats/Impl/LineAsStringRowInputFormat.cpp b/src/Processors/Formats/Impl/LineAsStringRowInputFormat.cpp index 3ade4c080b0..43adb5ec055 100644 --- a/src/Processors/Formats/Impl/LineAsStringRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/LineAsStringRowInputFormat.cpp @@ -87,7 +87,7 @@ static std::pair segmentationEngine(ReadBuffer & in, DB::Memory<> pos = find_first_symbols<'\n'>(pos, in.buffer().end()); if (pos > in.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (pos == in.buffer().end()) + if (pos == in.buffer().end()) continue; ++number_of_rows; diff --git a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp index 2d5e7f003f6..182c1faa68a 100644 --- a/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/NativeORCBlockInputFormat.cpp @@ -151,8 +151,7 @@ static DataTypePtr parseORCType(const orc::Type * orc_type, bool skip_columns_wi // In HIVE 0.11/0.12 precision is set as 0, but means max precision return createDecimal(38, 6); } - else - return createDecimal(precision, scale); + return createDecimal(precision, scale); } case orc::TypeKind::LIST: { if (subtype_count != 1) @@ -410,8 +409,7 @@ static bool evaluateRPNElement(const Field & field, const KeyCondition::RPNEleme case KeyCondition::RPNElement::FUNCTION_IS_NOT_NULL: { if (field.isNull()) return elem.function == KeyCondition::RPNElement::FUNCTION_IS_NULL; - else - return elem.function == KeyCondition::RPNElement::FUNCTION_IS_NOT_NULL; + return elem.function == KeyCondition::RPNElement::FUNCTION_IS_NOT_NULL; } default: throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected RPNElement Function {}", elem.toString()); @@ -740,7 +738,7 @@ static const orc::Type * traverseDownORCTypeByName( 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; } - else 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>". @@ -1478,17 +1476,13 @@ static ColumnWithTypeAndName readColumnFromORCColumn( if (precision <= DecimalUtils::max_precision) return readColumnWithDecimalDataCast(orc_column, orc_type, column_name, interal_type); - else if (precision <= DecimalUtils::max_precision) + if (precision <= DecimalUtils::max_precision) return readColumnWithDecimalDataCast(orc_column, orc_type, column_name, interal_type); - else if (precision <= DecimalUtils::max_precision) + if (precision <= DecimalUtils::max_precision) return readColumnWithDecimalDataCast( orc_column, orc_type, column_name, interal_type); - else - throw Exception( - ErrorCodes::ARGUMENT_OUT_OF_BOUND, - "Decimal precision {} in ORC type {} is out of bound", - precision, - orc_type->toString()); + throw Exception( + ErrorCodes::ARGUMENT_OUT_OF_BOUND, "Decimal precision {} in ORC type {} is out of bound", precision, orc_type->toString()); } case orc::MAP: { DataTypePtr key_type_hint; @@ -1658,16 +1652,14 @@ void ORCColumnToCHColumn::orcColumnsToCHChunk( { if (!allow_missing_columns) throw Exception{ErrorCodes::THERE_IS_NO_COLUMN, "Column '{}' is not presented in input data.", header_column.name}; - else - { - column.name = header_column.name; - column.type = header_column.type; - column.column = header_column.column->cloneResized(num_rows); - columns_list.push_back(std::move(column.column)); - if (block_missing_values) - block_missing_values->setBits(column_i, num_rows); - continue; - } + + column.name = header_column.name; + column.type = header_column.type; + column.column = header_column.column->cloneResized(num_rows); + columns_list.push_back(std::move(column.column)); + if (block_missing_values) + block_missing_values->setBits(column_i, num_rows); + continue; } } else diff --git a/src/Processors/Formats/Impl/NpyRowInputFormat.cpp b/src/Processors/Formats/Impl/NpyRowInputFormat.cpp index 773cbc9268e..acff1b4f38f 100644 --- a/src/Processors/Formats/Impl/NpyRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/NpyRowInputFormat.cpp @@ -141,22 +141,21 @@ std::shared_ptr parseType(String type) /// Parse type if (type[1] == 'i') return std::make_shared(endianness, parseTypeSize(type.substr(2)), true); - else if (type[1] == 'b') + if (type[1] == 'b') return std::make_shared(endianness, parseTypeSize(type.substr(2)), false); - else if (type[1] == 'u') + if (type[1] == 'u') return std::make_shared(endianness, parseTypeSize(type.substr(2)), false); - else if (type[1] == 'f') + if (type[1] == 'f') return std::make_shared(endianness, parseTypeSize(type.substr(2))); - else if (type[1] == 'S') + if (type[1] == 'S') return std::make_shared(endianness, parseTypeSize(type.substr(2))); - else if (type[1] == 'U') + if (type[1] == 'U') return std::make_shared(endianness, parseTypeSize(type.substr(2))); - else if (type[1] == 'c') + if (type[1] == 'c') throw Exception(ErrorCodes::BAD_ARGUMENTS, "ClickHouse doesn't support complex numeric type"); - else if (type[1] == 'O') + if (type[1] == 'O') throw Exception(ErrorCodes::BAD_ARGUMENTS, "ClickHouse doesn't support object types"); - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "ClickHouse doesn't support numpy type '{}'", type); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "ClickHouse doesn't support numpy type '{}'", type); } std::vector parseShape(String shape_string) diff --git a/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp b/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp index a7b22fe4592..aeaa090d0f3 100644 --- a/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/ORCBlockInputFormat.cpp @@ -67,7 +67,7 @@ Chunk ORCBlockInputFormat::read() /// 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(); - auto table = table_result.ValueOrDie(); + const auto & table = table_result.ValueOrDie(); if (!table || !num_rows) return {}; diff --git a/src/Processors/Formats/Impl/Parquet/ParquetLeafColReader.cpp b/src/Processors/Formats/Impl/Parquet/ParquetLeafColReader.cpp index 9e1cae9bb65..af499124dd7 100644 --- a/src/Processors/Formats/Impl/Parquet/ParquetLeafColReader.cpp +++ b/src/Processors/Formats/Impl/Parquet/ParquetLeafColReader.cpp @@ -201,9 +201,8 @@ std::unique_ptr createPlainReader( if (std::is_same_v> && col_des.physical_type() == parquet::Type::INT96) return std::make_unique>( col_des.max_definition_level(), std::move(def_level_reader), std::move(buffer)); - else - return std::make_unique>( - col_des.max_definition_level(), std::move(def_level_reader), std::move(buffer)); + return std::make_unique>( + col_des.max_definition_level(), std::move(def_level_reader), std::move(buffer)); } diff --git a/src/Processors/Formats/Impl/Parquet/ParquetRecordReader.cpp b/src/Processors/Formats/Impl/Parquet/ParquetRecordReader.cpp index 18a0db7484e..acf11a30162 100644 --- a/src/Processors/Formats/Impl/Parquet/ParquetRecordReader.cpp +++ b/src/Processors/Formats/Impl/Parquet/ParquetRecordReader.cpp @@ -211,7 +211,7 @@ std::unique_ptr ColReaderFactory::fromFLBA() { if (col_descriptor.type_length() <= static_cast(sizeof(Decimal128))) return makeDecimalLeafReader(); - else if (col_descriptor.type_length() <= static_cast(sizeof(Decimal256))) + if (col_descriptor.type_length() <= static_cast(sizeof(Decimal256))) return makeDecimalLeafReader(); } @@ -231,8 +231,7 @@ std::unique_ptr ColReaderFactory::fromInt32INT(const parque { if (int_type.is_signed()) return makeLeafReader(); - else - return makeLeafReader(); + return makeLeafReader(); } default: return throwUnsupported(PreformattedMessage::create(", bit width: {}", int_type.bit_width())); @@ -247,8 +246,7 @@ std::unique_ptr ColReaderFactory::fromInt64INT(const parque { if (int_type.is_signed()) return makeLeafReader(); - else - return makeLeafReader(); + return makeLeafReader(); } default: return throwUnsupported(PreformattedMessage::create(", bit width: {}", int_type.bit_width())); diff --git a/src/Processors/Formats/Impl/Parquet/Write.cpp b/src/Processors/Formats/Impl/Parquet/Write.cpp index b1e231d7749..7c0aab13a26 100644 --- a/src/Processors/Formats/Impl/Parquet/Write.cpp +++ b/src/Processors/Formats/Impl/Parquet/Write.cpp @@ -65,7 +65,7 @@ struct StatisticsNumeric memcpy(s.min_value.data(), &min, sizeof(T)); memcpy(s.max_value.data(), &max, sizeof(T)); - if constexpr (std::is_signed::value) + if constexpr (std::is_signed_v) { s.__set_min(s.min_value); s.__set_max(s.max_value); @@ -139,8 +139,8 @@ struct StatisticsFixedStringCopy { if (s.empty) return; - addMin(&s.min[0]); - addMax(&s.max[0]); + addMin(s.min.data()); + addMax(s.max.data()); empty = false; } diff --git a/src/Processors/Formats/Impl/ParquetBlockInputFormat.cpp b/src/Processors/Formats/Impl/ParquetBlockInputFormat.cpp index 82d5f186a9e..7384ce6cc1b 100644 --- a/src/Processors/Formats/Impl/ParquetBlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/ParquetBlockInputFormat.cpp @@ -134,12 +134,11 @@ static Field decodePlainParquetValueSlow(const std::string & data, parquet::Type }; if (size <= 4) return narrow(Decimal32(0)); - else if (size <= 8) + if (size <= 8) return narrow(Decimal64(0)); - else if (size <= 16) + if (size <= 16) return narrow(Decimal128(0)); - else - return narrow(Decimal256(0)); + return narrow(Decimal256(0)); } while (false); diff --git a/src/Processors/Formats/Impl/PrettyBlockOutputFormat.cpp b/src/Processors/Formats/Impl/PrettyBlockOutputFormat.cpp index ef3ef18e88d..ff1a048029d 100644 --- a/src/Processors/Formats/Impl/PrettyBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/PrettyBlockOutputFormat.cpp @@ -10,6 +10,8 @@ #include #include +#include + namespace DB { @@ -77,9 +79,9 @@ void PrettyBlockOutputFormat::calculateWidths( } widths[i][j] = UTF8::computeWidth(reinterpret_cast(serialized_value.data()), serialized_value.size(), prefix); - max_padded_widths[i] = std::max(max_padded_widths[i], - std::min(format_settings.pretty.max_column_pad_width, - std::min(format_settings.pretty.max_value_width, widths[i][j]))); + max_padded_widths[i] = std::max( + max_padded_widths[i], + std::min({format_settings.pretty.max_column_pad_width, format_settings.pretty.max_value_width, widths[i][j]})); } /// And also calculate widths for names of columns. @@ -553,7 +555,7 @@ void PrettyBlockOutputFormat::writeSuffix() void PrettyBlockOutputFormat::writeReadableNumberTip(const Chunk & chunk) { - auto columns = chunk.getColumns(); + const auto & columns = chunk.getColumns(); auto is_single_number = readable_number_tip && chunk.getNumRows() == 1 && chunk.getNumColumns() == 1; if (!is_single_number) return; diff --git a/src/Processors/Formats/Impl/PrometheusTextOutputFormat.cpp b/src/Processors/Formats/Impl/PrometheusTextOutputFormat.cpp index b43c195f201..865cdc11521 100644 --- a/src/Processors/Formats/Impl/PrometheusTextOutputFormat.cpp +++ b/src/Processors/Formats/Impl/PrometheusTextOutputFormat.cpp @@ -128,11 +128,11 @@ void PrometheusTextOutputFormat::fixupBucketLabels(CurrentMetric & metric) /// rows with labels at the beginning and then `_sum` and `_count` if (lhs_labels_contain_sum && rhs_labels_contain_count) return true; - else if (lhs_labels_contain_count && rhs_labels_contain_sum) + if (lhs_labels_contain_count && rhs_labels_contain_sum) return false; - else if (rhs_labels_contain_sum_or_count && !lhs_labels_contain_sum_or_count) + if (rhs_labels_contain_sum_or_count && !lhs_labels_contain_sum_or_count) return true; - else if (lhs_labels_contain_sum_or_count && !rhs_labels_contain_sum_or_count) + if (lhs_labels_contain_sum_or_count && !rhs_labels_contain_sum_or_count) return false; auto lit = lhs.labels.find(bucket_label); diff --git a/src/Processors/Formats/Impl/RegexpRowInputFormat.cpp b/src/Processors/Formats/Impl/RegexpRowInputFormat.cpp index 6c4422b36b5..2bb7011580c 100644 --- a/src/Processors/Formats/Impl/RegexpRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/RegexpRowInputFormat.cpp @@ -196,7 +196,7 @@ static std::pair segmentationEngine(ReadBuffer & in, DB::Memory<> pos = find_first_symbols<'\r', '\n'>(pos, in.buffer().end()); if (pos > in.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (pos == in.buffer().end()) + if (pos == in.buffer().end()) continue; ++number_of_rows; diff --git a/src/Processors/Formats/Impl/TSKVRowInputFormat.cpp b/src/Processors/Formats/Impl/TSKVRowInputFormat.cpp index 4d67bc1a4e9..8433f46ad18 100644 --- a/src/Processors/Formats/Impl/TSKVRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/TSKVRowInputFormat.cpp @@ -80,17 +80,14 @@ static bool readName(ReadBuffer & buf, StringRef & ref, String & tmp) return have_value; } /// The name has an escape sequence. - else - { - tmp.append(buf.position(), next_pos - buf.position()); - buf.position() += next_pos + 1 - buf.position(); - if (buf.eof()) - throw Exception(ErrorCodes::CANNOT_PARSE_ESCAPE_SEQUENCE, "Cannot parse escape sequence"); - tmp.push_back(parseEscapeSequence(*buf.position())); - ++buf.position(); - continue; - } + tmp.append(buf.position(), next_pos - buf.position()); + buf.position() += next_pos + 1 - buf.position(); + if (buf.eof()) + throw Exception(ErrorCodes::CANNOT_PARSE_ESCAPE_SEQUENCE, "Cannot parse escape sequence"); + + tmp.push_back(parseEscapeSequence(*buf.position())); + ++buf.position(); } throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Unexpected end of stream while reading key name from TSKV format"); @@ -164,27 +161,26 @@ bool TSKVRowInputFormat::readRow(MutableColumns & columns, RowReadExtension & ex { throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Unexpected end of stream after field in TSKV format: {}", name_ref.toString()); } - else if (*in->position() == '\t') + if (*in->position() == '\t') { ++in->position(); continue; } - else if (*in->position() == '\n') + if (*in->position() == '\n') { ++in->position(); break; } - else - { - /// Possibly a garbage was written into column, remove it - if (index >= 0) - { - columns[index]->popBack(1); - seen_columns[index] = read_columns[index] = false; - } - throw Exception(ErrorCodes::CANNOT_PARSE_INPUT_ASSERTION_FAILED, "Found garbage after field in TSKV format: {}", name_ref.toString()); + /// Possibly a garbage was written into column, remove it + if (index >= 0) + { + columns[index]->popBack(1); + seen_columns[index] = read_columns[index] = false; } + + throw Exception( + ErrorCodes::CANNOT_PARSE_INPUT_ASSERTION_FAILED, "Found garbage after field in TSKV format: {}", name_ref.toString()); } } diff --git a/src/Processors/Formats/Impl/TabSeparatedRowInputFormat.cpp b/src/Processors/Formats/Impl/TabSeparatedRowInputFormat.cpp index d2e17e92924..f62ad01dc51 100644 --- a/src/Processors/Formats/Impl/TabSeparatedRowInputFormat.cpp +++ b/src/Processors/Formats/Impl/TabSeparatedRowInputFormat.cpp @@ -277,10 +277,8 @@ void TabSeparatedFormatReader::checkNullValueForNonNullable(DataTypePtr type) ++buf->position(); throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected NULL value of not Nullable type {}", type->getName()); } - else - { - --buf->position(); - } + + --buf->position(); } } } @@ -331,7 +329,7 @@ void TabSeparatedFormatReader::skipRow() if (istr.position() > istr.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (pos == istr.buffer().end()) + if (pos == istr.buffer().end()) continue; if (!is_raw && *istr.position() == '\\') @@ -349,7 +347,7 @@ void TabSeparatedFormatReader::skipRow() ++istr.position(); return; } - else if (*istr.position() == '\r') + if (*istr.position() == '\r') { ++istr.position(); if (!istr.eof() && *istr.position() == '\n') @@ -474,7 +472,7 @@ static std::pair fileSegmentationEngineTabSeparatedImpl(ReadBuffer if (pos > in.buffer().end()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Position in buffer is out of bounds. There must be a bug."); - else if (pos == in.buffer().end()) + if (pos == in.buffer().end()) continue; if (!is_raw && *pos == '\\') diff --git a/src/Processors/Formats/Impl/TemplateBlockOutputFormat.cpp b/src/Processors/Formats/Impl/TemplateBlockOutputFormat.cpp index 5d6db17aaa2..32d17cc7469 100644 --- a/src/Processors/Formats/Impl/TemplateBlockOutputFormat.cpp +++ b/src/Processors/Formats/Impl/TemplateBlockOutputFormat.cpp @@ -74,26 +74,25 @@ TemplateBlockOutputFormat::ResultsetPart TemplateBlockOutputFormat::stringToResu { if (part == "data") return ResultsetPart::Data; - else if (part == "totals") + if (part == "totals") return ResultsetPart::Totals; - else if (part == "min") + if (part == "min") return ResultsetPart::ExtremesMin; - else if (part == "max") + if (part == "max") return ResultsetPart::ExtremesMax; - else if (part == "rows") + if (part == "rows") return ResultsetPart::Rows; - else if (part == "rows_before_limit") + if (part == "rows_before_limit") return ResultsetPart::RowsBeforeLimit; - else if (part == "time") + if (part == "time") return ResultsetPart::TimeElapsed; - else if (part == "rows_read") + if (part == "rows_read") return ResultsetPart::RowsRead; - else if (part == "bytes_read") + if (part == "bytes_read") return ResultsetPart::BytesRead; - else if (part == "rows_before_aggregation") + if (part == "rows_before_aggregation") return ResultsetPart::RowsBeforeAggregation; - else - throw Exception(ErrorCodes::SYNTAX_ERROR, "Unknown output part {}", part); + throw Exception(ErrorCodes::SYNTAX_ERROR, "Unknown output part {}", part); } void TemplateBlockOutputFormat::writeRow(const Chunk & chunk, size_t row_num) diff --git a/src/Processors/Formats/Impl/ValuesBlockInputFormat.cpp b/src/Processors/Formats/Impl/ValuesBlockInputFormat.cpp index 95bc8d4edb7..6f94b901de9 100644 --- a/src/Processors/Formats/Impl/ValuesBlockInputFormat.cpp +++ b/src/Processors/Formats/Impl/ValuesBlockInputFormat.cpp @@ -475,7 +475,7 @@ bool ValuesBlockInputFormat::parseExpression(IColumn & column, size_t column_idx parser_type_for_column[column_idx] = ParserType::Streaming; return true; } - else if (rollback_on_exception) + if (rollback_on_exception) column.popBack(1); } @@ -586,13 +586,11 @@ bool ValuesBlockInputFormat::checkDelimiterAfterValue(size_t column_idx) { return checkChar(',', *buf); } - else - { - /// Optional trailing comma. - if (checkChar(',', *buf)) - skipWhitespaceIfAny(*buf); - return checkChar(')', *buf); - } + + /// Optional trailing comma. + if (checkChar(',', *buf)) + skipWhitespaceIfAny(*buf); + return checkChar(')', *buf); } bool ValuesBlockInputFormat::shouldDeduceNewTemplate(size_t column_idx) diff --git a/src/Processors/Merges/Algorithms/Graphite.cpp b/src/Processors/Merges/Algorithms/Graphite.cpp index 0865ec8c0bb..460f1bea4b2 100644 --- a/src/Processors/Merges/Algorithms/Graphite.cpp +++ b/src/Processors/Merges/Algorithms/Graphite.cpp @@ -52,14 +52,13 @@ RuleType ruleType(const String & s) { if (s == "all") return RuleTypeAll; - else if (s == "plain") + if (s == "plain") return RuleTypePlain; - else if (s == "tagged") + if (s == "tagged") return RuleTypeTagged; - else if (s == "tag_list") + if (s == "tag_list") return RuleTypeTagList; - else - throw Exception(DB::ErrorCodes::BAD_ARGUMENTS, "invalid rule type: {}", s); + throw Exception(DB::ErrorCodes::BAD_ARGUMENTS, "invalid rule type: {}", s); } void Pattern::updateHash(SipHash & hash) const @@ -96,13 +95,10 @@ inline static const Patterns & selectPatternsForMetricType(const Graphite::Param std::string_view path_view = path; if (path_view.find("?"sv) == std::string::npos) return params.patterns_plain; - else - return params.patterns_tagged; - } - else - { - return params.patterns; + return params.patterns_tagged; } + + return params.patterns; } Graphite::RollupRule selectPatternForPath( @@ -177,7 +173,7 @@ static bool compareRetentions(const Retention & a, const Retention & b) { return true; } - else if (a.age < b.age && a.precision < b.precision) + if (a.age < b.age && a.precision < b.precision) { return false; } diff --git a/src/Processors/Merges/Algorithms/GraphiteRollupSortedAlgorithm.cpp b/src/Processors/Merges/Algorithms/GraphiteRollupSortedAlgorithm.cpp index 2b891592b20..a34081107a8 100644 --- a/src/Processors/Merges/Algorithms/GraphiteRollupSortedAlgorithm.cpp +++ b/src/Processors/Merges/Algorithms/GraphiteRollupSortedAlgorithm.cpp @@ -98,12 +98,10 @@ static time_t roundTimeToPrecision(const DateLUTImpl & date_lut, time_t time, UI { return time / precision * precision; } - else - { - time_t date = date_lut.toDate(time); - time_t remainder = time - date; - return date + remainder / precision * precision; - } + + time_t date = date_lut.toDate(time); + time_t remainder = time - date; + return date + remainder / precision * precision; } IMergingAlgorithm::Status GraphiteRollupSortedAlgorithm::merge() diff --git a/src/Processors/QueryPlan/DistinctStep.cpp b/src/Processors/QueryPlan/DistinctStep.cpp index 1e95d0fd689..f124e5a2b9f 100644 --- a/src/Processors/QueryPlan/DistinctStep.cpp +++ b/src/Processors/QueryPlan/DistinctStep.cpp @@ -74,29 +74,14 @@ void DistinctStep::transformPipeline(QueryPipelineBuilder & pipeline, const Buil }); return; } + /// final distinct for sorted stream (sorting inside and among chunks) - else + if (pipeline.getNumStreams() != 1) + throw Exception(ErrorCodes::LOGICAL_ERROR, "DistinctStep with in-order expects single input"); + + if (distinct_sort_desc.size() < columns.size()) { - if (pipeline.getNumStreams() != 1) - throw Exception(ErrorCodes::LOGICAL_ERROR, "DistinctStep with in-order expects single input"); - - if (distinct_sort_desc.size() < columns.size()) - { - if (DistinctSortedTransform::isApplicable(pipeline.getHeader(), distinct_sort_desc, columns)) - { - pipeline.addSimpleTransform( - [&](const Block & header, QueryPipelineBuilder::StreamType stream_type) -> ProcessorPtr - { - if (stream_type != QueryPipelineBuilder::StreamType::Main) - return nullptr; - - return std::make_shared( - header, distinct_sort_desc, set_size_limits, limit_hint, columns); - }); - return; - } - } - else + if (DistinctSortedTransform::isApplicable(pipeline.getHeader(), distinct_sort_desc, columns)) { pipeline.addSimpleTransform( [&](const Block & header, QueryPipelineBuilder::StreamType stream_type) -> ProcessorPtr @@ -104,12 +89,25 @@ void DistinctStep::transformPipeline(QueryPipelineBuilder & pipeline, const Buil if (stream_type != QueryPipelineBuilder::StreamType::Main) return nullptr; - return std::make_shared( - header, set_size_limits, limit_hint, distinct_sort_desc, columns); + return std::make_shared( + header, distinct_sort_desc, set_size_limits, limit_hint, columns); }); return; } } + else + { + pipeline.addSimpleTransform( + [&](const Block & header, QueryPipelineBuilder::StreamType stream_type) -> ProcessorPtr + { + if (stream_type != QueryPipelineBuilder::StreamType::Main) + return nullptr; + + return std::make_shared( + header, set_size_limits, limit_hint, distinct_sort_desc, columns); + }); + return; + } } } diff --git a/src/Processors/QueryPlan/Optimizations/mergeExpressions.cpp b/src/Processors/QueryPlan/Optimizations/mergeExpressions.cpp index fb4cb90c4ca..8ecd9989fa0 100644 --- a/src/Processors/QueryPlan/Optimizations/mergeExpressions.cpp +++ b/src/Processors/QueryPlan/Optimizations/mergeExpressions.cpp @@ -55,7 +55,7 @@ size_t tryMergeExpressions(QueryPlan::Node * parent_node, QueryPlan::Nodes &) parent_node->children.swap(child_node->children); return 1; } - else if (parent_filter && child_expr) + if (parent_filter && child_expr) { auto & child_actions = child_expr->getExpression(); auto & parent_actions = parent_filter->getExpression(); @@ -65,10 +65,11 @@ size_t tryMergeExpressions(QueryPlan::Node * parent_node, QueryPlan::Nodes &) auto merged = ActionsDAG::merge(std::move(child_actions), std::move(parent_actions)); - auto filter = std::make_unique(child_expr->getInputStreams().front(), - std::move(merged), - parent_filter->getFilterColumnName(), - parent_filter->removesFilterColumn()); + auto filter = std::make_unique( + child_expr->getInputStreams().front(), + std::move(merged), + parent_filter->getFilterColumnName(), + parent_filter->removesFilterColumn()); filter->setStepDescription("(" + parent_filter->getStepDescription() + " + " + child_expr->getStepDescription() + ")"); parent_node->step = std::move(filter); diff --git a/src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp b/src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp index a23ff9fe93a..a053b774e07 100644 --- a/src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp +++ b/src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.cpp @@ -824,7 +824,7 @@ InputOrderInfoPtr buildInputOrderInfo(SortingStep & sorting, QueryPlan::Node & n return order_info; } - else if (auto * merge = typeid_cast(reading_node->step.get())) + if (auto * merge = typeid_cast(reading_node->step.get())) { auto order_info = buildInputOrderFromSortDescription( merge, @@ -880,7 +880,7 @@ InputOrder buildInputOrderInfo(AggregatingStep & aggregating, QueryPlan::Node & return order_info; } - else if (auto * merge = typeid_cast(reading_node->step.get())) + if (auto * merge = typeid_cast(reading_node->step.get())) { auto order_info = buildInputOrderFromUnorderedKeys( merge, @@ -967,7 +967,7 @@ InputOrder buildInputOrderInfo(DistinctStep & distinct, QueryPlan::Node & node) return order_info; } - else if (auto * merge = typeid_cast(reading_node->step.get())) + if (auto * merge = typeid_cast(reading_node->step.get())) { auto order_info = buildInputOrderFromUnorderedKeys( merge, diff --git a/src/Processors/QueryPlan/Optimizations/removeRedundantDistinct.cpp b/src/Processors/QueryPlan/Optimizations/removeRedundantDistinct.cpp index 6eb5e3c1f3f..ef13a5f85a6 100644 --- a/src/Processors/QueryPlan/Optimizations/removeRedundantDistinct.cpp +++ b/src/Processors/QueryPlan/Optimizations/removeRedundantDistinct.cpp @@ -206,8 +206,8 @@ namespace return compareAggregationKeysWithDistinctColumns( aggregating_step->getParams().keys, distinct_columns, std::move(actions_chain)); } - else if (const auto * merging_aggregated_step = typeid_cast(aggregation_before_distinct); - merging_aggregated_step) + if (const auto * merging_aggregated_step = typeid_cast(aggregation_before_distinct); + merging_aggregated_step) { return compareAggregationKeysWithDistinctColumns( merging_aggregated_step->getParams().keys, distinct_columns, std::move(actions_chain)); diff --git a/src/Processors/QueryPlan/Optimizations/removeRedundantSorting.cpp b/src/Processors/QueryPlan/Optimizations/removeRedundantSorting.cpp index f0094f0f8d2..3c67e68f704 100644 --- a/src/Processors/QueryPlan/Optimizations/removeRedundantSorting.cpp +++ b/src/Processors/QueryPlan/Optimizations/removeRedundantSorting.cpp @@ -181,7 +181,7 @@ private: return true; } /// (2) sorting - else if (const auto * next_sorting = typeid_cast(step_affect_order); next_sorting) + if (const auto * next_sorting = typeid_cast(step_affect_order); next_sorting) { if (next_sorting->getType() == SortingStep::Type::Full) return true; diff --git a/src/Processors/QueryPlan/PartsSplitter.cpp b/src/Processors/QueryPlan/PartsSplitter.cpp index aaa1f53b5ee..57fd41e2a32 100644 --- a/src/Processors/QueryPlan/PartsSplitter.cpp +++ b/src/Processors/QueryPlan/PartsSplitter.cpp @@ -256,7 +256,7 @@ struct PartsRangesIterator int compare_result = compareValues(value, other.value); if (compare_result == -1) return true; - else if (compare_result == 1) + if (compare_result == 1) return false; if (event == other.event) diff --git a/src/Processors/QueryPlan/ReadFromMemoryStorageStep.cpp b/src/Processors/QueryPlan/ReadFromMemoryStorageStep.cpp index 538e35ea554..e1bdae760dd 100644 --- a/src/Processors/QueryPlan/ReadFromMemoryStorageStep.cpp +++ b/src/Processors/QueryPlan/ReadFromMemoryStorageStep.cpp @@ -88,10 +88,8 @@ private: { return (*parallel_execution_index)++; } - else - { - return execution_index++; - } + + return execution_index++; } const NamesAndTypesList requested_column_names_and_types; diff --git a/src/Processors/QueryPlan/ReadFromMergeTree.cpp b/src/Processors/QueryPlan/ReadFromMergeTree.cpp index da9f18586e0..9f2700d7def 100644 --- a/src/Processors/QueryPlan/ReadFromMergeTree.cpp +++ b/src/Processors/QueryPlan/ReadFromMergeTree.cpp @@ -1441,8 +1441,7 @@ Pipe ReadFromMergeTree::spreadMarkRangesAmongStreamsFinal( }); return Pipe::unitePipes(std::move(pipes)); } - else - return merging_pipes.empty() ? Pipe::unitePipes(std::move(no_merging_pipes)) : Pipe::unitePipes(std::move(merging_pipes)); + return merging_pipes.empty() ? Pipe::unitePipes(std::move(no_merging_pipes)) : Pipe::unitePipes(std::move(merging_pipes)); } ReadFromMergeTree::AnalysisResultPtr ReadFromMergeTree::selectRangesToRead(bool find_exact_ranges) const @@ -1933,8 +1932,7 @@ bool ReadFromMergeTree::isQueryWithSampling() const const auto & select = query_info.query->as(); if (query_info.table_expression_modifiers) return query_info.table_expression_modifiers->getSampleSizeRatio() != std::nullopt; - else - return select.sampleSize() != nullptr; + return select.sampleSize() != nullptr; } Pipe ReadFromMergeTree::spreadMarkRanges( @@ -1988,15 +1986,13 @@ Pipe ReadFromMergeTree::spreadMarkRanges( return spreadMarkRangesAmongStreamsFinal(std::move(parts_with_ranges), num_streams, result.column_names_to_read, column_names_to_read, result_projection); } - else if (query_info.input_order_info) + if (query_info.input_order_info) { return spreadMarkRangesAmongStreamsWithOrder( std::move(parts_with_ranges), num_streams, column_names_to_read, result_projection, query_info.input_order_info); } - else - { - return spreadMarkRangesAmongStreams(std::move(parts_with_ranges), num_streams, column_names_to_read); - } + + return spreadMarkRangesAmongStreams(std::move(parts_with_ranges), num_streams, column_names_to_read); } Pipe ReadFromMergeTree::groupStreamsByPartition(AnalysisResult & result, std::optional & result_projection) diff --git a/src/Processors/QueryPlan/ReadFromRemote.cpp b/src/Processors/QueryPlan/ReadFromRemote.cpp index 39ea6f03922..1fe1141e161 100644 --- a/src/Processors/QueryPlan/ReadFromRemote.cpp +++ b/src/Processors/QueryPlan/ReadFromRemote.cpp @@ -209,25 +209,23 @@ void ReadFromRemote::addLazyPipe(Pipes & pipes, const ClusterProxy::SelectStream QueryPlanOptimizationSettings::fromContext(my_context), BuildQueryPipelineSettings::fromContext(my_context))); } - else - { - std::vector connections; - connections.reserve(try_results.size()); - for (auto & try_result : try_results) - connections.emplace_back(std::move(try_result.entry)); - String query_string = formattedAST(query); + std::vector connections; + connections.reserve(try_results.size()); + for (auto & try_result : try_results) + connections.emplace_back(std::move(try_result.entry)); - my_scalars["_shard_num"] - = Block{{DataTypeUInt32().createColumnConst(1, my_shard.shard_info.shard_num), std::make_shared(), "_shard_num"}}; - auto remote_query_executor = std::make_shared( - std::move(connections), query_string, header, my_context, my_throttler, my_scalars, my_external_tables, my_stage); + String query_string = formattedAST(query); - auto pipe = createRemoteSourcePipe(remote_query_executor, add_agg_info, add_totals, add_extremes, async_read, async_query_sending); - QueryPipelineBuilder builder; - builder.init(std::move(pipe)); - return builder; - } + my_scalars["_shard_num"] = Block{ + {DataTypeUInt32().createColumnConst(1, my_shard.shard_info.shard_num), std::make_shared(), "_shard_num"}}; + auto remote_query_executor = std::make_shared( + std::move(connections), query_string, header, my_context, my_throttler, my_scalars, my_external_tables, my_stage); + + auto pipe = createRemoteSourcePipe(remote_query_executor, add_agg_info, add_totals, add_extremes, async_read, async_query_sending); + QueryPipelineBuilder builder; + builder.init(std::move(pipe)); + return builder; }; pipes.emplace_back(createDelayedPipe(shard.header, lazily_create_stream, add_totals, add_extremes)); diff --git a/src/Processors/QueryPlan/ReadFromSystemNumbersStep.cpp b/src/Processors/QueryPlan/ReadFromSystemNumbersStep.cpp index 2855793ea2c..fa6811dd2db 100644 --- a/src/Processors/QueryPlan/ReadFromSystemNumbersStep.cpp +++ b/src/Processors/QueryPlan/ReadFromSystemNumbersStep.cpp @@ -377,18 +377,16 @@ void shrinkRanges(RangesWithStep & ranges, size_t size) size -= static_cast(range_size); continue; } - else if (range_size == size) + if (range_size == size) { last_range_idx = i; break; } - else - { - auto & range = ranges[i]; - range.size = static_cast(size); - last_range_idx = i; - break; - } + + auto & range = ranges[i]; + range.size = static_cast(size); + last_range_idx = i; + break; } /// delete the additional ranges diff --git a/src/Processors/Sources/MongoDBPocoLegacySource.cpp b/src/Processors/Sources/MongoDBPocoLegacySource.cpp index c1775b1a252..d39b857ee28 100644 --- a/src/Processors/Sources/MongoDBPocoLegacySource.cpp +++ b/src/Processors/Sources/MongoDBPocoLegacySource.cpp @@ -143,7 +143,7 @@ namespace String string_id = value.toString(); return Field(string_id.data(), string_id.size()); } - else if (value.type() == Poco::MongoDB::ElementTraits::TypeId) + if (value.type() == Poco::MongoDB::ElementTraits::TypeId) { String string = static_cast &>(value).value(); return Field(string.data(), string.size()); @@ -179,14 +179,14 @@ namespace String string = static_cast &>(value).value(); return parse(string); } - else if (value.type() == Poco::MongoDB::ElementTraits::TypeId) + if (value.type() == Poco::MongoDB::ElementTraits::TypeId) { const Poco::UUID & poco_uuid = static_cast &>(value).value()->uuid(); return parsePocoUUID(poco_uuid); } - else - throw Exception(ErrorCodes::TYPE_MISMATCH, "Type mismatch, expected String/UUID, got type id = {} for column {}", - toString(value.type()), name); + + throw Exception(ErrorCodes::TYPE_MISMATCH, "Type mismatch, expected String/UUID, got type id = {} for column {}", + toString(value.type()), name); }; else throw Exception(ErrorCodes::BAD_ARGUMENTS, "Type conversion to {} is not supported", nested->getName()); @@ -279,7 +279,7 @@ namespace assert_cast(column).insertData(string_id.data(), string_id.size()); break; } - else if (value.type() == Poco::MongoDB::ElementTraits::TypeId) + if (value.type() == Poco::MongoDB::ElementTraits::TypeId) { String string = static_cast &>(value).value(); assert_cast(column).insertData(string.data(), string.size()); @@ -467,12 +467,10 @@ Poco::MongoDB::Document::Vector MongoDBPocoLegacyCursor::nextDocuments(Poco::Mon cursor_id = response.cursorID(); return std::move(response.documents()); } - else - { - auto response = new_cursor->next(connection); - cursor_id = new_cursor->cursorID(); - return std::move(response.documents()); - } + + auto response = new_cursor->next(connection); + cursor_id = new_cursor->cursorID(); + return std::move(response.documents()); } Int64 MongoDBPocoLegacyCursor::cursorID() const diff --git a/src/Processors/Sources/SQLiteSource.cpp b/src/Processors/Sources/SQLiteSource.cpp index 79c4be7f692..ce44bebd847 100644 --- a/src/Processors/Sources/SQLiteSource.cpp +++ b/src/Processors/Sources/SQLiteSource.cpp @@ -65,16 +65,19 @@ Chunk SQLiteSource::generate() { continue; } - else if (status == SQLITE_DONE) + if (status == SQLITE_DONE) { compiled_statement.reset(); break; } - else if (status != SQLITE_ROW) + if (status != SQLITE_ROW) { - throw Exception(ErrorCodes::SQLITE_ENGINE_ERROR, + throw Exception( + ErrorCodes::SQLITE_ENGINE_ERROR, "Expected SQLITE_ROW status, but got status {}. Error: {}, Message: {}", - status, sqlite3_errstr(status), sqlite3_errmsg(sqlite_db.get())); + status, + sqlite3_errstr(status), + sqlite3_errmsg(sqlite_db.get())); } int column_count = sqlite3_column_count(compiled_statement.get()); diff --git a/src/Processors/Sources/ShellCommandSource.cpp b/src/Processors/Sources/ShellCommandSource.cpp index f55a3713215..cc3ac58b6f6 100644 --- a/src/Processors/Sources/ShellCommandSource.cpp +++ b/src/Processors/Sources/ShellCommandSource.cpp @@ -173,9 +173,8 @@ public: std::string_view str(stderr_read_buf.get(), res); if (stderr_reaction == ExternalCommandStderrReaction::THROW) throw Exception(ErrorCodes::UNSUPPORTED_METHOD, "Executable generates stderr: {}", str); - else if (stderr_reaction == ExternalCommandStderrReaction::LOG) - LOG_WARNING( - getLogger("TimeoutReadBufferFromFileDescriptor"), "Executable generates stderr: {}", str); + if (stderr_reaction == ExternalCommandStderrReaction::LOG) + LOG_WARNING(getLogger("TimeoutReadBufferFromFileDescriptor"), "Executable generates stderr: {}", str); else if (stderr_reaction == ExternalCommandStderrReaction::LOG_FIRST) { res = std::min(ssize_t(stderr_result_buf.reserve()), res); @@ -610,8 +609,7 @@ Pipe ShellCommandSourceCoordinator::createPipe( { if (execute_direct) return ShellCommand::executeDirect(command_config); - else - return ShellCommand::execute(command_config); + return ShellCommand::execute(command_config); }; return std::make_unique(std::move(func)); diff --git a/src/Processors/Sources/SourceFromChunks.cpp b/src/Processors/Sources/SourceFromChunks.cpp index 9fad508c23b..bc25bf7a6f0 100644 --- a/src/Processors/Sources/SourceFromChunks.cpp +++ b/src/Processors/Sources/SourceFromChunks.cpp @@ -22,8 +22,7 @@ Chunk SourceFromChunks::generate() it++; return chunk; } - else - return {}; + return {}; } } diff --git a/src/Processors/TTL/ITTLAlgorithm.cpp b/src/Processors/TTL/ITTLAlgorithm.cpp index 761f43e2422..b2c44798c42 100644 --- a/src/Processors/TTL/ITTLAlgorithm.cpp +++ b/src/Processors/TTL/ITTLAlgorithm.cpp @@ -50,13 +50,13 @@ UInt32 ITTLAlgorithm::getTimestampByIndex(const IColumn * column, size_t index) { if (const ColumnUInt16 * column_date = typeid_cast(column)) return static_cast(date_lut.fromDayNum(DayNum(column_date->getData()[index]))); - else if (const ColumnUInt32 * column_date_time = typeid_cast(column)) + if (const ColumnUInt32 * column_date_time = typeid_cast(column)) return column_date_time->getData()[index]; - else if (const ColumnConst * column_const = typeid_cast(column)) + if (const ColumnConst * column_const = typeid_cast(column)) { if (typeid_cast(&column_const->getDataColumn())) return static_cast(date_lut.fromDayNum(DayNum(column_const->getValue()))); - else if (typeid_cast(&column_const->getDataColumn())) + if (typeid_cast(&column_const->getDataColumn())) return column_const->getValue(); } diff --git a/src/Processors/Transforms/AddingDefaultsTransform.cpp b/src/Processors/Transforms/AddingDefaultsTransform.cpp index e7bdf8b6ff3..a15ea9d67cb 100644 --- a/src/Processors/Transforms/AddingDefaultsTransform.cpp +++ b/src/Processors/Transforms/AddingDefaultsTransform.cpp @@ -83,7 +83,7 @@ static void mixNumberColumns( return true; } - else if (auto col_defs = checkAndGetColumn(col_defaults.get())) + if (auto col_defs = checkAndGetColumn(col_defaults.get())) { auto & src = col_defs->getData(); for (size_t i = 0; i < defaults_mask.size(); ++i) diff --git a/src/Processors/Transforms/AggregatingInOrderTransform.cpp b/src/Processors/Transforms/AggregatingInOrderTransform.cpp index f8bc419b623..f5b0aeb5e14 100644 --- a/src/Processors/Transforms/AggregatingInOrderTransform.cpp +++ b/src/Processors/Transforms/AggregatingInOrderTransform.cpp @@ -257,29 +257,25 @@ IProcessor::Status AggregatingInOrderTransform::prepare() { return Status::Ready; } - else - { - output.push(std::move(to_push_chunk)); - return Status::Ready; - } - } - else - { - if (is_consume_finished) - { - output.push(std::move(to_push_chunk)); - output.finish(); - LOG_DEBUG(log, "Aggregated. {} to {} rows (from {})", - src_rows, res_rows, formatReadableSizeWithBinarySuffix(src_bytes)); - return Status::Finished; - } - if (input.isFinished()) - { - is_consume_finished = true; - return Status::Ready; - } + output.push(std::move(to_push_chunk)); + return Status::Ready; } + + if (is_consume_finished) + { + output.push(std::move(to_push_chunk)); + output.finish(); + LOG_DEBUG(log, "Aggregated. {} to {} rows (from {})", src_rows, res_rows, formatReadableSizeWithBinarySuffix(src_bytes)); + return Status::Finished; + } + + if (input.isFinished()) + { + is_consume_finished = true; + return Status::Ready; + } + if (!input.hasData()) { input.setNeeded(); diff --git a/src/Processors/Transforms/AggregatingTransform.cpp b/src/Processors/Transforms/AggregatingTransform.cpp index 2e21df0f387..68f23898018 100644 --- a/src/Processors/Transforms/AggregatingTransform.cpp +++ b/src/Processors/Transforms/AggregatingTransform.cpp @@ -609,12 +609,10 @@ IProcessor::Status AggregatingTransform::prepare() many_data.reset(); return Status::Finished; } - else - { - /// Finish data processing and create another pipe. - is_consume_finished = true; - return Status::Ready; - } + + /// Finish data processing and create another pipe. + is_consume_finished = true; + return Status::Ready; } if (!input.hasData()) diff --git a/src/Processors/Transforms/CheckSortedTransform.cpp b/src/Processors/Transforms/CheckSortedTransform.cpp index a2ba8e21ba3..412692e9be6 100644 --- a/src/Processors/Transforms/CheckSortedTransform.cpp +++ b/src/Processors/Transforms/CheckSortedTransform.cpp @@ -39,14 +39,16 @@ void CheckSortedTransform::transform(Chunk & chunk) { return; } - else if (res > 0) + if (res > 0) { - throw Exception(ErrorCodes::LOGICAL_ERROR, + throw Exception( + ErrorCodes::LOGICAL_ERROR, "Sort order of blocks violated for column number {}, left: {}, right: {}. Chunk {}, rows read {}.{}", column_number, applyVisitor(FieldVisitorDump(), (*left_col)[left_index]), applyVisitor(FieldVisitorDump(), (*right_col)[right_index]), - chunk_num, rows_read, + chunk_num, + rows_read, description.empty() ? String() : fmt::format(" ({})", description)); } } diff --git a/src/Processors/Transforms/ColumnGathererTransform.h b/src/Processors/Transforms/ColumnGathererTransform.h index ce2671ce0bf..f136de65e9b 100644 --- a/src/Processors/Transforms/ColumnGathererTransform.h +++ b/src/Processors/Transforms/ColumnGathererTransform.h @@ -190,7 +190,7 @@ void ColumnGathererStream::gather(Column & column_res) source_to_fully_copy = &source; return; } - else if (len == 1) + if (len == 1) column_res.insertFrom(*source.column, source.pos); else column_res.insertRangeFrom(*source.column, source.pos, len); diff --git a/src/Processors/Transforms/MergeJoinTransform.cpp b/src/Processors/Transforms/MergeJoinTransform.cpp index 6abfa0fccd0..1675e5d0386 100644 --- a/src/Processors/Transforms/MergeJoinTransform.cpp +++ b/src/Processors/Transforms/MergeJoinTransform.cpp @@ -646,14 +646,13 @@ void dispatchKind(JoinKind kind, Args && ... args) { if (Impl::enabled && kind == JoinKind::Inner) return Impl::join(std::forward(args)...); - else if (Impl::enabled && kind == JoinKind::Left) + if (Impl::enabled && kind == JoinKind::Left) return Impl::join(std::forward(args)...); - else if (Impl::enabled && kind == JoinKind::Right) + if (Impl::enabled && kind == JoinKind::Right) return Impl::join(std::forward(args)...); - else if (Impl::enabled && kind == JoinKind::Full) + if (Impl::enabled && kind == JoinKind::Full) return Impl::join(std::forward(args)...); - else - throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Unsupported join kind: \"{}\"", kind); + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Unsupported join kind: \"{}\"", kind); } MutableColumns MergeJoinAlgorithm::getEmptyResultColumns() const @@ -1103,7 +1102,7 @@ MergeJoinAlgorithm::Status MergeJoinAlgorithm::asofJoin() throw Exception(ErrorCodes::NOT_IMPLEMENTED, "TODO: implement ASOF equality join"); } - else if (cmp < 0) + if (cmp < 0) { if (asof_join_state.hasMatch(left_cursor, asof_inequality)) { @@ -1116,10 +1115,9 @@ MergeJoinAlgorithm::Status MergeJoinAlgorithm::asofJoin() left_cursor->next(); continue; } - else - { - asof_join_state.reset(); - } + + asof_join_state.reset(); + /// no matches for rows in left table, just pass them through size_t num = nextDistinct(*left_cursor); diff --git a/src/Processors/Transforms/PartialSortingTransform.cpp b/src/Processors/Transforms/PartialSortingTransform.cpp index e79673f6645..57e21aefd9f 100644 --- a/src/Processors/Transforms/PartialSortingTransform.cpp +++ b/src/Processors/Transforms/PartialSortingTransform.cpp @@ -74,7 +74,7 @@ bool compareWithThreshold(const ColumnRawPtrs & raw_block_columns, size_t min_bl if (res < 0) return true; - else if (res > 0) + if (res > 0) return false; } diff --git a/src/Processors/Transforms/SortingTransform.cpp b/src/Processors/Transforms/SortingTransform.cpp index 8e7a526864d..6e65093e9e2 100644 --- a/src/Processors/Transforms/SortingTransform.cpp +++ b/src/Processors/Transforms/SortingTransform.cpp @@ -319,29 +319,27 @@ IProcessor::Status SortingTransform::prepareGenerate() output.push(std::move(generated_chunk)); return Status::PortFull; } - else + + auto & input = inputs.back(); + + if (generated_chunk) + output.push(std::move(generated_chunk)); + + if (input.isFinished()) { - auto & input = inputs.back(); - - if (generated_chunk) - output.push(std::move(generated_chunk)); - - if (input.isFinished()) - { - output.finish(); - return Status::Finished; - } - - input.setNeeded(); - - if (!input.hasData()) - return Status::NeedData; - - auto chunk = input.pull(); - enrichChunkWithConstants(chunk); - output.push(std::move(chunk)); - return Status::PortFull; + output.finish(); + return Status::Finished; } + + input.setNeeded(); + + if (!input.hasData()) + return Status::NeedData; + + auto chunk = input.pull(); + enrichChunkWithConstants(chunk); + output.push(std::move(chunk)); + return Status::PortFull; } void SortingTransform::work() diff --git a/src/Processors/Transforms/WindowTransform.cpp b/src/Processors/Transforms/WindowTransform.cpp index bd11aa4cd28..6f43a8e4b24 100644 --- a/src/Processors/Transforms/WindowTransform.cpp +++ b/src/Processors/Transforms/WindowTransform.cpp @@ -23,6 +23,7 @@ #include #include +#include #include @@ -112,18 +113,13 @@ static int compareValuesWithOffset(const IColumn * _compared_column, // We know that because offset is >= 0. return 1; } - else - { - // Overflow to the positive, [compared] must be less. - return -1; - } - } - else - { - // No overflow, compare normally. - return compared_value < reference_value ? -1 - : compared_value == reference_value ? 0 : 1; + + // Overflow to the positive, [compared] must be less. + return -1; } + + // No overflow, compare normally. + return compared_value < reference_value ? -1 : compared_value == reference_value ? 0 : 1; } // A specialization of compareValuesWithOffset for floats. @@ -216,11 +212,11 @@ static int compareValuesWithOffsetNullable(const IColumn * _compared_column, { return -1; } - else if (compared_column->isNullAt(compared_row) && reference_column->isNullAt(reference_row)) + if (compared_column->isNullAt(compared_row) && reference_column->isNullAt(reference_row)) { return 0; } - else if (!compared_column->isNullAt(compared_row) && reference_column->isNullAt(reference_row)) + if (!compared_column->isNullAt(compared_row) && reference_column->isNullAt(reference_row)) { return 1; } @@ -1484,8 +1480,7 @@ void WindowTransform::work() // that the frame start can be further than current row for some frame specs // (e.g. EXCLUDE CURRENT ROW), so we have to check both. assert(prev_frame_start <= frame_start); - const auto first_used_block = std::min(next_output_block_number, - std::min(prev_frame_start.block, current_row.block)); + const auto first_used_block = std::min({next_output_block_number, prev_frame_start.block, current_row.block}); if (first_block_number < first_used_block) { blocks.erase(blocks.begin(), diff --git a/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp b/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp index 1f6474da7d0..648ed9751ff 100644 --- a/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp +++ b/src/Processors/Transforms/getSourceFromASTInsertQuery.cpp @@ -53,8 +53,7 @@ InputFormatPtr getInputFormatFromASTInsertQuery( { if (input_function) throw Exception(ErrorCodes::INVALID_USAGE_OF_INPUT, "FORMAT must be specified for function input()"); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "INSERT query requires format to be set"); + throw Exception(ErrorCodes::LOGICAL_ERROR, "INSERT query requires format to be set"); } /// Data could be in parsed (ast_insert_query.data) and in not parsed yet (input_buffer_tail_part) part of query. diff --git a/src/QueryPipeline/QueryPipeline.cpp b/src/QueryPipeline/QueryPipeline.cpp index 492ef7186b2..cab9e7a68fb 100644 --- a/src/QueryPipeline/QueryPipeline.cpp +++ b/src/QueryPipeline/QueryPipeline.cpp @@ -566,12 +566,9 @@ Block QueryPipeline::getHeader() const { if (input) return input->getHeader(); - else if (output) + if (output) return output->getHeader(); - else - throw Exception( - ErrorCodes::LOGICAL_ERROR, - "Header is available only for pushing or pulling QueryPipeline"); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Header is available only for pushing or pulling QueryPipeline"); } void QueryPipeline::setProgressCallback(const ProgressCallback & callback) diff --git a/src/QueryPipeline/QueryPipelineBuilder.cpp b/src/QueryPipeline/QueryPipelineBuilder.cpp index d276fed60a2..526f02466d1 100644 --- a/src/QueryPipeline/QueryPipelineBuilder.cpp +++ b/src/QueryPipeline/QueryPipelineBuilder.cpp @@ -373,11 +373,9 @@ std::unique_ptr QueryPipelineBuilder::joinPipelinesYShaped auto joining = std::make_shared(join, inputs, out_header, max_block_size); return mergePipelines(std::move(left), std::move(right), std::move(joining), collected_processors); } - else - { - auto joining = std::make_shared(join, inputs, out_header, max_block_size); - return mergePipelines(std::move(left), std::move(right), std::move(joining), collected_processors); - } + + auto joining = std::make_shared(join, inputs, out_header, max_block_size); + return mergePipelines(std::move(left), std::move(right), std::move(joining), collected_processors); } std::unique_ptr QueryPipelineBuilder::joinPipelinesRightLeft( diff --git a/src/QueryPipeline/RemoteInserter.cpp b/src/QueryPipeline/RemoteInserter.cpp index 9c0ffe221dd..b958924f008 100644 --- a/src/QueryPipeline/RemoteInserter.cpp +++ b/src/QueryPipeline/RemoteInserter.cpp @@ -68,12 +68,12 @@ RemoteInserter::RemoteInserter( header = packet.block; break; } - else if (Protocol::Server::Exception == packet.type) + if (Protocol::Server::Exception == packet.type) { packet.exception->rethrow(); break; } - else if (Protocol::Server::Log == packet.type) + if (Protocol::Server::Log == packet.type) { /// Pass logs from remote server to client if (auto log_queue = CurrentThread::getInternalTextLogsQueue()) @@ -133,7 +133,7 @@ void RemoteInserter::onFinish() if (Protocol::Server::EndOfStream == packet.type) break; - else if (Protocol::Server::Exception == packet.type) + if (Protocol::Server::Exception == packet.type) packet.exception->rethrow(); else if (Protocol::Server::Log == packet.type || Protocol::Server::TimezoneUpdate == packet.type) { diff --git a/src/QueryPipeline/RemoteQueryExecutor.cpp b/src/QueryPipeline/RemoteQueryExecutor.cpp index 7aeb7ec1bab..5faae03bc8f 100644 --- a/src/QueryPipeline/RemoteQueryExecutor.cpp +++ b/src/QueryPipeline/RemoteQueryExecutor.cpp @@ -570,8 +570,7 @@ RemoteQueryExecutor::ReadResult RemoteQueryExecutor::restartQueryWithoutDuplicat /// Consecutive read will implicitly send query first. if (!read_context) return read(); - else - return readAsync(); + return readAsync(); } RemoteQueryExecutor::ReadResult RemoteQueryExecutor::processPacket(Packet packet) diff --git a/src/Server/GRPCServer.cpp b/src/Server/GRPCServer.cpp index 3aa651c89c9..48caa9236ef 100644 --- a/src/Server/GRPCServer.cpp +++ b/src/Server/GRPCServer.cpp @@ -1005,14 +1005,12 @@ namespace { if (!insert_query) throw Exception(ErrorCodes::NO_DATA_TO_INSERT, "Query requires data to insert, but it is not an INSERT query"); - else - { - const auto & settings = query_context->getSettingsRef(); - if (settings[Setting::throw_if_no_data_to_insert]) - throw Exception(ErrorCodes::NO_DATA_TO_INSERT, "No data to insert"); - else - return; - } + + const auto & settings = query_context->getSettingsRef(); + if (settings[Setting::throw_if_no_data_to_insert]) + throw Exception(ErrorCodes::NO_DATA_TO_INSERT, "No data to insert"); + + return; } /// This is significant, because parallel parsing may be used. @@ -1486,8 +1484,7 @@ namespace { if (initial_query_info_read) throw Exception(ErrorCodes::NETWORK_ERROR, "Failed to read extra QueryInfo"); - else - throw Exception(ErrorCodes::NETWORK_ERROR, "Failed to read initial QueryInfo"); + throw Exception(ErrorCodes::NETWORK_ERROR, "Failed to read initial QueryInfo"); } } diff --git a/src/Server/HTTP/WriteBufferFromHTTPServerResponse.cpp b/src/Server/HTTP/WriteBufferFromHTTPServerResponse.cpp index 47af568838a..c0c285cf0f1 100644 --- a/src/Server/HTTP/WriteBufferFromHTTPServerResponse.cpp +++ b/src/Server/HTTP/WriteBufferFromHTTPServerResponse.cpp @@ -13,28 +13,28 @@ namespace DB void WriteBufferFromHTTPServerResponse::startSendHeaders() { - if (!headers_started_sending) + if (headers_started_sending) + return; + + headers_started_sending = true; + + if (!response.getChunkedTransferEncoding() && response.getContentLength() == Poco::Net::HTTPMessage::UNKNOWN_CONTENT_LENGTH) { - headers_started_sending = true; - - if (!response.getChunkedTransferEncoding() && response.getContentLength() == Poco::Net::HTTPMessage::UNKNOWN_CONTENT_LENGTH) - { - /// In case there is no Content-Length we cannot use keep-alive, - /// since there is no way to know when the server send all the - /// data, so "Connection: close" should be sent. - response.setKeepAlive(false); - } - - if (add_cors_header) - response.set("Access-Control-Allow-Origin", "*"); - - setResponseDefaultHeaders(response); - - std::stringstream header; //STYLE_CHECK_ALLOW_STD_STRING_STREAM - response.beginWrite(header); - auto header_str = header.str(); - socketSendBytes(header_str.data(), header_str.size()); + /// In case there is no Content-Length we cannot use keep-alive, + /// since there is no way to know when the server send all the + /// data, so "Connection: close" should be sent. + response.setKeepAlive(false); } + + if (add_cors_header) + response.set("Access-Control-Allow-Origin", "*"); + + setResponseDefaultHeaders(response); + + std::stringstream header; //STYLE_CHECK_ALLOW_STD_STRING_STREAM + response.beginWrite(header); + auto header_str = header.str(); + socketSendBytes(header_str.data(), header_str.size()); } void WriteBufferFromHTTPServerResponse::writeHeaderProgressImpl(const char * header_name) diff --git a/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp b/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp index 6de57217aac..f17e4f25ce4 100644 --- a/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp +++ b/src/Server/HTTP/exceptionCodeToHTTPStatus.cpp @@ -75,79 +75,58 @@ Poco::Net::HTTPResponse::HTTPStatus exceptionCodeToHTTPStatus(int exception_code { return HTTPResponse::HTTP_UNAUTHORIZED; } - else if (exception_code == ErrorCodes::UNKNOWN_USER || - exception_code == ErrorCodes::WRONG_PASSWORD || - exception_code == ErrorCodes::AUTHENTICATION_FAILED || - exception_code == ErrorCodes::SET_NON_GRANTED_ROLE) + if (exception_code == ErrorCodes::UNKNOWN_USER || exception_code == ErrorCodes::WRONG_PASSWORD + || exception_code == ErrorCodes::AUTHENTICATION_FAILED || exception_code == ErrorCodes::SET_NON_GRANTED_ROLE) { return HTTPResponse::HTTP_FORBIDDEN; } - else if (exception_code == ErrorCodes::BAD_ARGUMENTS || - exception_code == ErrorCodes::CANNOT_COMPILE_REGEXP || - exception_code == ErrorCodes::CANNOT_PARSE_TEXT || - exception_code == ErrorCodes::CANNOT_PARSE_ESCAPE_SEQUENCE || - exception_code == ErrorCodes::CANNOT_PARSE_QUOTED_STRING || - exception_code == ErrorCodes::CANNOT_PARSE_DATE || - exception_code == ErrorCodes::CANNOT_PARSE_DATETIME || - exception_code == ErrorCodes::CANNOT_PARSE_NUMBER || - exception_code == ErrorCodes::CANNOT_PARSE_DOMAIN_VALUE_FROM_STRING || - exception_code == ErrorCodes::CANNOT_PARSE_IPV4 || - exception_code == ErrorCodes::CANNOT_PARSE_IPV6 || - exception_code == ErrorCodes::CANNOT_PARSE_INPUT_ASSERTION_FAILED || - exception_code == ErrorCodes::CANNOT_PARSE_UUID || - exception_code == ErrorCodes::DUPLICATE_COLUMN || - exception_code == ErrorCodes::ILLEGAL_COLUMN || - exception_code == ErrorCodes::UNKNOWN_ELEMENT_IN_AST || - exception_code == ErrorCodes::UNKNOWN_TYPE_OF_AST_NODE || - exception_code == ErrorCodes::THERE_IS_NO_COLUMN || - exception_code == ErrorCodes::TOO_DEEP_AST || - exception_code == ErrorCodes::TOO_BIG_AST || - exception_code == ErrorCodes::UNEXPECTED_AST_STRUCTURE || - exception_code == ErrorCodes::SYNTAX_ERROR || - exception_code == ErrorCodes::INCORRECT_DATA || - exception_code == ErrorCodes::TYPE_MISMATCH || - exception_code == ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) + if (exception_code == ErrorCodes::BAD_ARGUMENTS || exception_code == ErrorCodes::CANNOT_COMPILE_REGEXP + || exception_code == ErrorCodes::CANNOT_PARSE_TEXT || exception_code == ErrorCodes::CANNOT_PARSE_ESCAPE_SEQUENCE + || exception_code == ErrorCodes::CANNOT_PARSE_QUOTED_STRING || exception_code == ErrorCodes::CANNOT_PARSE_DATE + || exception_code == ErrorCodes::CANNOT_PARSE_DATETIME || exception_code == ErrorCodes::CANNOT_PARSE_NUMBER + || exception_code == ErrorCodes::CANNOT_PARSE_DOMAIN_VALUE_FROM_STRING || exception_code == ErrorCodes::CANNOT_PARSE_IPV4 + || exception_code == ErrorCodes::CANNOT_PARSE_IPV6 || exception_code == ErrorCodes::CANNOT_PARSE_INPUT_ASSERTION_FAILED + || exception_code == ErrorCodes::CANNOT_PARSE_UUID || exception_code == ErrorCodes::DUPLICATE_COLUMN + || exception_code == ErrorCodes::ILLEGAL_COLUMN || exception_code == ErrorCodes::UNKNOWN_ELEMENT_IN_AST + || exception_code == ErrorCodes::UNKNOWN_TYPE_OF_AST_NODE || exception_code == ErrorCodes::THERE_IS_NO_COLUMN + || exception_code == ErrorCodes::TOO_DEEP_AST || exception_code == ErrorCodes::TOO_BIG_AST + || exception_code == ErrorCodes::UNEXPECTED_AST_STRUCTURE || exception_code == ErrorCodes::SYNTAX_ERROR + || exception_code == ErrorCodes::INCORRECT_DATA || exception_code == ErrorCodes::TYPE_MISMATCH + || exception_code == ErrorCodes::VALUE_IS_OUT_OF_RANGE_OF_DATA_TYPE) { return HTTPResponse::HTTP_BAD_REQUEST; } - else if (exception_code == ErrorCodes::UNKNOWN_TABLE || - exception_code == ErrorCodes::UNKNOWN_FUNCTION || - exception_code == ErrorCodes::UNKNOWN_IDENTIFIER || - exception_code == ErrorCodes::UNKNOWN_TYPE || - exception_code == ErrorCodes::UNKNOWN_STORAGE || - exception_code == ErrorCodes::UNKNOWN_DATABASE || - exception_code == ErrorCodes::UNKNOWN_SETTING || - exception_code == ErrorCodes::UNKNOWN_DIRECTION_OF_SORTING || - exception_code == ErrorCodes::UNKNOWN_AGGREGATE_FUNCTION || - exception_code == ErrorCodes::UNKNOWN_FORMAT || - exception_code == ErrorCodes::UNKNOWN_DATABASE_ENGINE || - exception_code == ErrorCodes::UNKNOWN_TYPE_OF_QUERY || - exception_code == ErrorCodes::UNKNOWN_ROLE) + if (exception_code == ErrorCodes::UNKNOWN_TABLE || exception_code == ErrorCodes::UNKNOWN_FUNCTION + || exception_code == ErrorCodes::UNKNOWN_IDENTIFIER || exception_code == ErrorCodes::UNKNOWN_TYPE + || exception_code == ErrorCodes::UNKNOWN_STORAGE || exception_code == ErrorCodes::UNKNOWN_DATABASE + || exception_code == ErrorCodes::UNKNOWN_SETTING || exception_code == ErrorCodes::UNKNOWN_DIRECTION_OF_SORTING + || exception_code == ErrorCodes::UNKNOWN_AGGREGATE_FUNCTION || exception_code == ErrorCodes::UNKNOWN_FORMAT + || exception_code == ErrorCodes::UNKNOWN_DATABASE_ENGINE || exception_code == ErrorCodes::UNKNOWN_TYPE_OF_QUERY + || exception_code == ErrorCodes::UNKNOWN_ROLE) { return HTTPResponse::HTTP_NOT_FOUND; } - else if (exception_code == ErrorCodes::QUERY_IS_TOO_LARGE) + if (exception_code == ErrorCodes::QUERY_IS_TOO_LARGE) { return HTTPResponse::HTTP_REQUESTENTITYTOOLARGE; } - else if (exception_code == ErrorCodes::NOT_IMPLEMENTED) + if (exception_code == ErrorCodes::NOT_IMPLEMENTED) { return HTTPResponse::HTTP_NOT_IMPLEMENTED; } - else if (exception_code == ErrorCodes::SOCKET_TIMEOUT || - exception_code == ErrorCodes::CANNOT_OPEN_FILE) + if (exception_code == ErrorCodes::SOCKET_TIMEOUT || exception_code == ErrorCodes::CANNOT_OPEN_FILE) { return HTTPResponse::HTTP_SERVICE_UNAVAILABLE; } - else if (exception_code == ErrorCodes::HTTP_LENGTH_REQUIRED) + if (exception_code == ErrorCodes::HTTP_LENGTH_REQUIRED) { return HTTPResponse::HTTP_LENGTH_REQUIRED; } - else if (exception_code == ErrorCodes::TIMEOUT_EXCEEDED) + if (exception_code == ErrorCodes::TIMEOUT_EXCEEDED) { return HTTPResponse::HTTP_REQUEST_TIMEOUT; } - else if (exception_code == ErrorCodes::CANNOT_SCHEDULE_TASK) + if (exception_code == ErrorCodes::CANNOT_SCHEDULE_TASK) { return HTTPResponse::HTTP_SERVICE_UNAVAILABLE; } diff --git a/src/Server/HTTPHandlerFactory.cpp b/src/Server/HTTPHandlerFactory.cpp index fc31ad2874e..a99f0a50a4b 100644 --- a/src/Server/HTTPHandlerFactory.cpp +++ b/src/Server/HTTPHandlerFactory.cpp @@ -172,12 +172,10 @@ createHTTPHandlerFactory(IServer & server, const Poco::Util::AbstractConfigurati { return createHandlersFactoryFromConfig(server, config, name, "http_handlers", async_metrics); } - else - { - auto factory = std::make_shared(name); - addDefaultHandlersFactory(*factory, server, config, async_metrics); - return factory; - } + + auto factory = std::make_shared(name); + addDefaultHandlersFactory(*factory, server, config, async_metrics); + return factory; } static inline HTTPRequestHandlerFactoryPtr createInterserverHTTPHandlerFactory(IServer & server, const std::string & name) @@ -197,9 +195,9 @@ HTTPRequestHandlerFactoryPtr createHandlerFactory(IServer & server, const Poco:: { if (name == "HTTPHandler-factory" || name == "HTTPSHandler-factory") return createHTTPHandlerFactory(server, config, name, async_metrics); - else if (name == "InterserverIOHTTPHandler-factory" || name == "InterserverIOHTTPSHandler-factory") + if (name == "InterserverIOHTTPHandler-factory" || name == "InterserverIOHTTPSHandler-factory") return createInterserverHTTPHandlerFactory(server, name); - else if (name == "PrometheusHandler-factory") + if (name == "PrometheusHandler-factory") return createPrometheusHandlerFactory(server, config, async_metrics, name); throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown HTTP handler factory name."); diff --git a/src/Server/HTTPHandlerFactory.h b/src/Server/HTTPHandlerFactory.h index db4bb73cbc4..cbb0cdee1dd 100644 --- a/src/Server/HTTPHandlerFactory.h +++ b/src/Server/HTTPHandlerFactory.h @@ -52,7 +52,7 @@ public: { if (filter_type == "handler") continue; - else if (filter_type == "url") + if (filter_type == "url") addFilter(urlFilter(config, prefix + ".url")); else if (filter_type == "empty_query_string") addFilter(emptyQueryStringFilter()); diff --git a/src/Server/InterserverIOHTTPHandler.cpp b/src/Server/InterserverIOHTTPHandler.cpp index 59852c79139..5c6a8516d0f 100644 --- a/src/Server/InterserverIOHTTPHandler.cpp +++ b/src/Server/InterserverIOHTTPHandler.cpp @@ -41,7 +41,7 @@ std::pair InterserverIOHTTPHandler::checkAuthentication(HTTPServer Poco::Net::HTTPBasicCredentials credentials(info); return server_credentials->isValidUser(credentials.getUsername(), credentials.getPassword()); } - else if (request.hasCredentials()) + if (request.hasCredentials()) { return {"Client requires HTTP Basic authentication, but server doesn't provide it", false}; } diff --git a/src/Server/KeeperTCPHandler.cpp b/src/Server/KeeperTCPHandler.cpp index fe746e34805..f908395aaef 100644 --- a/src/Server/KeeperTCPHandler.cpp +++ b/src/Server/KeeperTCPHandler.cpp @@ -547,29 +547,27 @@ bool KeeperTCPHandler::tryExecuteFourLetterWordCmd(int32_t command) LOG_WARNING(log, "invalid four letter command {}", IFourLetterCommand::toName(command)); return false; } - else if (!FourLetterCommandFactory::instance().isEnabled(command)) + if (!FourLetterCommandFactory::instance().isEnabled(command)) { LOG_WARNING(log, "Not enabled four letter command {}", IFourLetterCommand::toName(command)); return false; } - else + + auto command_ptr = FourLetterCommandFactory::instance().get(command); + LOG_DEBUG(log, "Receive four letter command {}", command_ptr->name()); + + try { - auto command_ptr = FourLetterCommandFactory::instance().get(command); - LOG_DEBUG(log, "Receive four letter command {}", command_ptr->name()); - - try - { - String res = command_ptr->run(); - out->write(res.data(),res.size()); - out->next(); - } - catch (...) - { - tryLogCurrentException(log, "Error when executing four letter command " + command_ptr->name()); - } - - return true; + String res = command_ptr->run(); + out->write(res.data(), res.size()); + out->next(); } + catch (...) + { + tryLogCurrentException(log, "Error when executing four letter command " + command_ptr->name()); + } + + return true; } WriteBuffer & KeeperTCPHandler::getWriteBuffer() diff --git a/src/Server/PrometheusRequestHandlerFactory.cpp b/src/Server/PrometheusRequestHandlerFactory.cpp index 52f1d3b64c1..1dcdc71e46f 100644 --- a/src/Server/PrometheusRequestHandlerFactory.cpp +++ b/src/Server/PrometheusRequestHandlerFactory.cpp @@ -101,12 +101,12 @@ namespace if (type == "expose_metrics") return parseExposeMetricsConfig(config, config_prefix); - else if (type == "remote_write") + if (type == "remote_write") return parseRemoteWriteConfig(config, config_prefix); - else if (type == "remote_read") + if (type == "remote_read") return parseRemoteReadConfig(config, config_prefix); - else - throw Exception(ErrorCodes::UNKNOWN_ELEMENT_IN_CONFIG, "Unknown type {} is specified in the configuration for a prometheus protocol", type); + throw Exception( + ErrorCodes::UNKNOWN_ELEMENT_IN_CONFIG, "Unknown type {} is specified in the configuration for a prometheus protocol", type); } /// Returns true if the protocol represented by a passed config can be handled. @@ -122,8 +122,7 @@ namespace { if (for_keeper) return std::make_unique(); - else - return std::make_unique(); + return std::make_unique(); } /// Base function for making a factory for PrometheusRequestHandler. This function can return nullptr. diff --git a/src/Server/TCPHandler.cpp b/src/Server/TCPHandler.cpp index dadaf614f92..8104ab87084 100644 --- a/src/Server/TCPHandler.cpp +++ b/src/Server/TCPHandler.cpp @@ -1062,7 +1062,7 @@ void TCPHandler::processInsertQuery() sendInsertProfileEvents(); return; } - else if (result.status == AsynchronousInsertQueue::PushResult::TOO_MUCH_DATA) + if (result.status == AsynchronousInsertQueue::PushResult::TOO_MUCH_DATA) { LOG_DEBUG(log, "Setting async_insert=1, but INSERT query will be executed synchronously because it has too much data"); processed_block = std::move(result.insert_block); @@ -1138,7 +1138,7 @@ void TCPHandler::processOrdinaryQuery() executor.cancel(); break; } - else if (cancellation_status == CancellationStatus::READ_CANCELLED) + if (cancellation_status == CancellationStatus::READ_CANCELLED) { executor.cancelReading(); } @@ -1543,9 +1543,8 @@ void TCPHandler::receiveHello() writeString(formatHTTPErrorResponseWhenUserIsConnectedToWrongPort(server.config()), *out); throw Exception(ErrorCodes::CLIENT_HAS_CONNECTED_TO_WRONG_PORT, "Client has connected to wrong port"); } - else - throw NetException(ErrorCodes::UNEXPECTED_PACKET_FROM_CLIENT, - "Unexpected packet from client (expected Hello, got {})", packet_type); + throw NetException( + ErrorCodes::UNEXPECTED_PACKET_FROM_CLIENT, "Unexpected packet from client (expected Hello, got {})", packet_type); } readStringBinary(client_name, *in); @@ -1830,11 +1829,11 @@ String TCPHandler::receiveReadTaskResponseAssumeLocked() decreaseCancellationStatus("Received 'Cancel' packet from the client, canceling the read task."); return {}; } - else - { - throw Exception(ErrorCodes::UNEXPECTED_PACKET_FROM_CLIENT, "Received {} packet after requesting read task", - Protocol::Client::toString(packet_type)); - } + + throw Exception( + ErrorCodes::UNEXPECTED_PACKET_FROM_CLIENT, + "Received {} packet after requesting read task", + Protocol::Client::toString(packet_type)); } UInt64 version; readVarUInt(version, *in); @@ -1857,11 +1856,11 @@ std::optional TCPHandler::receivePartitionMergeTreeReadTas decreaseCancellationStatus("Received 'Cancel' packet from the client, canceling the MergeTree read task."); return std::nullopt; } - else - { - throw Exception(ErrorCodes::UNEXPECTED_PACKET_FROM_CLIENT, "Received {} packet after requesting read task", - Protocol::Client::toString(packet_type)); - } + + throw Exception( + ErrorCodes::UNEXPECTED_PACKET_FROM_CLIENT, + "Received {} packet after requesting read task", + Protocol::Client::toString(packet_type)); } ParallelReadResponse response; response.deserialize(*in); @@ -2540,8 +2539,7 @@ Poco::Net::SocketAddress TCPHandler::getClientAddress(const ClientInfo & client_ String forwarded_address = client_info.getLastForwardedFor(); if (!forwarded_address.empty() && server.config().getBool("auth_use_forwarded_address", false)) return Poco::Net::SocketAddress(forwarded_address, socket().peerAddress().port()); - else - return socket().peerAddress(); + return socket().peerAddress(); } } diff --git a/src/Storages/AlterCommands.cpp b/src/Storages/AlterCommands.cpp index 7b402464562..7c328526ab7 100644 --- a/src/Storages/AlterCommands.cpp +++ b/src/Storages/AlterCommands.cpp @@ -76,19 +76,19 @@ AlterCommand::RemoveProperty removePropertyFromString(const String & property) { if (property.empty()) return AlterCommand::RemoveProperty::NO_PROPERTY; - else if (property == "DEFAULT") + if (property == "DEFAULT") return AlterCommand::RemoveProperty::DEFAULT; - else if (property == "MATERIALIZED") + if (property == "MATERIALIZED") return AlterCommand::RemoveProperty::MATERIALIZED; - else if (property == "ALIAS") + if (property == "ALIAS") return AlterCommand::RemoveProperty::ALIAS; - else if (property == "COMMENT") + if (property == "COMMENT") return AlterCommand::RemoveProperty::COMMENT; - else if (property == "CODEC") + if (property == "CODEC") return AlterCommand::RemoveProperty::CODEC; - else if (property == "TTL") + if (property == "TTL") return AlterCommand::RemoveProperty::TTL; - else if (property == "SETTINGS") + if (property == "SETTINGS") return AlterCommand::RemoveProperty::SETTINGS; throw Exception(ErrorCodes::BAD_ARGUMENTS, "Cannot remove unknown property '{}'", property); @@ -142,7 +142,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ return command; } - else if (command_ast->type == ASTAlterCommand::DROP_COLUMN) + if (command_ast->type == ASTAlterCommand::DROP_COLUMN) { AlterCommand command; command.ast = command_ast->clone(); @@ -156,7 +156,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.partition = command_ast->partition->clone(); return command; } - else if (command_ast->type == ASTAlterCommand::MODIFY_COLUMN) + if (command_ast->type == ASTAlterCommand::MODIFY_COLUMN) { AlterCommand command; command.ast = command_ast->clone(); @@ -216,7 +216,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ return command; } - else if (command_ast->type == ASTAlterCommand::COMMENT_COLUMN) + if (command_ast->type == ASTAlterCommand::COMMENT_COLUMN) { AlterCommand command; command.ast = command_ast->clone(); @@ -227,7 +227,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.if_exists = command_ast->if_exists; return command; } - else if (command_ast->type == ASTAlterCommand::MODIFY_COMMENT) + if (command_ast->type == ASTAlterCommand::MODIFY_COMMENT) { AlterCommand command; command.ast = command_ast->clone(); @@ -236,7 +236,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.comment = ast_comment.value.safeGet(); return command; } - else if (command_ast->type == ASTAlterCommand::MODIFY_ORDER_BY) + if (command_ast->type == ASTAlterCommand::MODIFY_ORDER_BY) { AlterCommand command; command.ast = command_ast->clone(); @@ -244,7 +244,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.order_by = command_ast->order_by->clone(); return command; } - else if (command_ast->type == ASTAlterCommand::MODIFY_SAMPLE_BY) + if (command_ast->type == ASTAlterCommand::MODIFY_SAMPLE_BY) { AlterCommand command; command.ast = command_ast->clone(); @@ -252,14 +252,14 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.sample_by = command_ast->sample_by->clone(); return command; } - else if (command_ast->type == ASTAlterCommand::REMOVE_SAMPLE_BY) + if (command_ast->type == ASTAlterCommand::REMOVE_SAMPLE_BY) { AlterCommand command; command.ast = command_ast->clone(); command.type = AlterCommand::REMOVE_SAMPLE_BY; return command; } - else if (command_ast->type == ASTAlterCommand::ADD_INDEX) + if (command_ast->type == ASTAlterCommand::ADD_INDEX) { AlterCommand command; command.ast = command_ast->clone(); @@ -278,7 +278,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ return command; } - else if (command_ast->type == ASTAlterCommand::ADD_STATISTICS) + if (command_ast->type == ASTAlterCommand::ADD_STATISTICS) { AlterCommand command; command.ast = command_ast->clone(); @@ -293,7 +293,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ return command; } - else if (command_ast->type == ASTAlterCommand::MODIFY_STATISTICS) + if (command_ast->type == ASTAlterCommand::MODIFY_STATISTICS) { AlterCommand command; command.ast = command_ast->clone(); @@ -308,7 +308,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ return command; } - else if (command_ast->type == ASTAlterCommand::ADD_CONSTRAINT) + if (command_ast->type == ASTAlterCommand::ADD_CONSTRAINT) { AlterCommand command; command.ast = command_ast->clone(); @@ -323,7 +323,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ return command; } - else if (command_ast->type == ASTAlterCommand::ADD_PROJECTION) + if (command_ast->type == ASTAlterCommand::ADD_PROJECTION) { AlterCommand command; command.ast = command_ast->clone(); @@ -342,7 +342,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ return command; } - else if (command_ast->type == ASTAlterCommand::DROP_CONSTRAINT) + if (command_ast->type == ASTAlterCommand::DROP_CONSTRAINT) { AlterCommand command; command.ast = command_ast->clone(); @@ -352,7 +352,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ return command; } - else if (command_ast->type == ASTAlterCommand::DROP_INDEX) + if (command_ast->type == ASTAlterCommand::DROP_INDEX) { AlterCommand command; command.ast = command_ast->clone(); @@ -367,7 +367,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ return command; } - else if (command_ast->type == ASTAlterCommand::DROP_STATISTICS) + if (command_ast->type == ASTAlterCommand::DROP_STATISTICS) { AlterCommand command; command.ast = command_ast->clone(); @@ -384,7 +384,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ return command; } - else if (command_ast->type == ASTAlterCommand::DROP_PROJECTION) + if (command_ast->type == ASTAlterCommand::DROP_PROJECTION) { AlterCommand command; command.ast = command_ast->clone(); @@ -399,7 +399,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ return command; } - else if (command_ast->type == ASTAlterCommand::MODIFY_TTL) + if (command_ast->type == ASTAlterCommand::MODIFY_TTL) { AlterCommand command; command.ast = command_ast->clone(); @@ -407,14 +407,14 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.ttl = command_ast->ttl->clone(); return command; } - else if (command_ast->type == ASTAlterCommand::REMOVE_TTL) + if (command_ast->type == ASTAlterCommand::REMOVE_TTL) { AlterCommand command; command.ast = command_ast->clone(); command.type = AlterCommand::REMOVE_TTL; return command; } - else if (command_ast->type == ASTAlterCommand::MODIFY_SETTING) + if (command_ast->type == ASTAlterCommand::MODIFY_SETTING) { AlterCommand command; command.ast = command_ast->clone(); @@ -422,7 +422,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.settings_changes = command_ast->settings_changes->as().changes; return command; } - else if (command_ast->type == ASTAlterCommand::MODIFY_DATABASE_SETTING) + if (command_ast->type == ASTAlterCommand::MODIFY_DATABASE_SETTING) { AlterCommand command; command.ast = command_ast->clone(); @@ -430,7 +430,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.settings_changes = command_ast->settings_changes->as().changes; return command; } - else if (command_ast->type == ASTAlterCommand::RESET_SETTING) + if (command_ast->type == ASTAlterCommand::RESET_SETTING) { AlterCommand command; command.ast = command_ast->clone(); @@ -444,7 +444,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ } return command; } - else if (command_ast->type == ASTAlterCommand::MODIFY_QUERY) + if (command_ast->type == ASTAlterCommand::MODIFY_QUERY) { AlterCommand command; command.ast = command_ast->clone(); @@ -452,7 +452,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.select = command_ast->select->clone(); return command; } - else if (command_ast->type == ASTAlterCommand::MODIFY_REFRESH) + if (command_ast->type == ASTAlterCommand::MODIFY_REFRESH) { AlterCommand command; command.ast = command_ast->clone(); @@ -460,7 +460,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.refresh = command_ast->refresh; return command; } - else if (command_ast->type == ASTAlterCommand::RENAME_COLUMN) + if (command_ast->type == ASTAlterCommand::RENAME_COLUMN) { AlterCommand command; command.ast = command_ast->clone(); @@ -470,7 +470,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.if_exists = command_ast->if_exists; return command; } - else if (command_ast->type == ASTAlterCommand::MODIFY_SQL_SECURITY) + if (command_ast->type == ASTAlterCommand::MODIFY_SQL_SECURITY) { AlterCommand command; command.ast = command_ast->clone(); @@ -478,8 +478,8 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.sql_security = command_ast->sql_security->clone(); return command; } - else - return {}; + + return {}; } @@ -648,8 +648,7 @@ void AlterCommand::apply(StorageInMemoryMetadata & metadata, ContextPtr context) { if (if_not_exists) return; - else - throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot add index {}: index with this name already exists", index_name); + throw Exception(ErrorCodes::ILLEGAL_COLUMN, "Cannot add index {}: index with this name already exists", index_name); } auto insert_it = metadata.secondary_indices.end(); @@ -1026,13 +1025,9 @@ bool AlterCommand::isCommentAlter() const { return true; } - else if (type == MODIFY_COLUMN) + if (type == MODIFY_COLUMN) { - return comment.has_value() - && codec == nullptr - && data_type == nullptr - && default_expression == nullptr - && ttl == nullptr; + return comment.has_value() && codec == nullptr && data_type == nullptr && default_expression == nullptr && ttl == nullptr; } return false; } @@ -1357,8 +1352,7 @@ void AlterCommands::validate(const StoragePtr & table, ContextPtr context) const throw Exception(ErrorCodes::DUPLICATE_COLUMN, "Cannot add column {}: column with this name already exists", backQuote(column_name)); - else - continue; + continue; } if (!command.data_type) @@ -1402,8 +1396,7 @@ void AlterCommands::validate(const StoragePtr & table, ContextPtr context) const throw Exception(ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK, "Wrong column. Cannot find column {} to modify{}", backQuote(column_name), all_columns.getHintsMessage(column_name)); } - else - continue; + continue; } if (renamed_columns.contains(column_name)) @@ -1578,9 +1571,11 @@ void AlterCommands::validate(const StoragePtr & table, ContextPtr context) const { if (next_command.column_name == command.rename_to) throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Transitive renames in a single ALTER query are not allowed (don't make sense)"); - else if (next_command.column_name == command.column_name) - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Cannot rename column '{}' to two different names in a single ALTER query", - backQuote(command.column_name)); + if (next_command.column_name == command.column_name) + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Cannot rename column '{}' to two different names in a single ALTER query", + backQuote(command.column_name)); } } @@ -1599,8 +1594,7 @@ void AlterCommands::validate(const StoragePtr & table, ContextPtr context) const all_columns.appendHintsMessage(message.text, command.column_name); throw Exception(std::move(message), ErrorCodes::NOT_FOUND_COLUMN_IN_BLOCK); } - else - continue; + continue; } if (all_columns.has(command.rename_to)) diff --git a/src/Storages/Cache/RemoteCacheController.cpp b/src/Storages/Cache/RemoteCacheController.cpp index 092cabc7239..b4a3a32438a 100644 --- a/src/Storages/Cache/RemoteCacheController.cpp +++ b/src/Storages/Cache/RemoteCacheController.cpp @@ -120,8 +120,7 @@ void RemoteCacheController::waitMoreData(size_t start_offset_, size_t end_offset lock.unlock(); return; } - else - more_data_signal.wait(lock, [this, end_offset_] { return file_status == DOWNLOADED || current_offset >= end_offset_; }); + more_data_signal.wait(lock, [this, end_offset_] { return file_status == DOWNLOADED || current_offset >= end_offset_; }); } lock.unlock(); } diff --git a/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp b/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp index c517a055044..53d62b7dd23 100644 --- a/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp +++ b/src/Storages/Distributed/DistributedAsyncInsertDirectoryQueue.cpp @@ -615,8 +615,7 @@ void DistributedAsyncInsertDirectoryQueue::processFilesWithBatching(const Settin tryLogCurrentException(log, "File is marked broken due to"); continue; } - else - throw; + throw; } BatchHeader batch_header( diff --git a/src/Storages/FileLog/FileLogConsumer.cpp b/src/Storages/FileLog/FileLogConsumer.cpp index 1bd3026ab8c..209c0530536 100644 --- a/src/Storages/FileLog/FileLogConsumer.cpp +++ b/src/Storages/FileLog/FileLogConsumer.cpp @@ -45,16 +45,14 @@ ReadBufferPtr FileLogConsumer::consume() LOG_TRACE(log, "No new records to read"); return nullptr; } - else - { - records = std::move(new_records); - current = records.begin(); - LOG_TRACE(log, "Polled batch of {} records. ", records.size()); + records = std::move(new_records); + current = records.begin(); - buffer_status = BufferStatus::POLLED_OK; - return getNextRecord(); - } + LOG_TRACE(log, "Polled batch of {} records. ", records.size()); + + buffer_status = BufferStatus::POLLED_OK; + return getNextRecord(); } FileLogConsumer::Records FileLogConsumer::pollBatch(size_t batch_size_) diff --git a/src/Storages/FileLog/FileLogDirectoryWatcher.cpp b/src/Storages/FileLog/FileLogDirectoryWatcher.cpp index 844b31fd7c9..09e4967c183 100644 --- a/src/Storages/FileLog/FileLogDirectoryWatcher.cpp +++ b/src/Storages/FileLog/FileLogDirectoryWatcher.cpp @@ -84,11 +84,9 @@ void FileLogDirectoryWatcher::onItemModified(DirectoryWatcherBase::DirectoryEven /// Already have MODIFY event for this file if (it->second.received_modification_event) return; - else - { - it->second.received_modification_event = true; - it->second.file_events.emplace_back(info); - } + + it->second.received_modification_event = true; + it->second.file_events.emplace_back(info); } else { diff --git a/src/Storages/FileLog/FileLogSource.cpp b/src/Storages/FileLog/FileLogSource.cpp index eb3ff0436a5..7f7d21b62c8 100644 --- a/src/Storages/FileLog/FileLogSource.cpp +++ b/src/Storages/FileLog/FileLogSource.cpp @@ -105,10 +105,8 @@ Chunk FileLogSource::generate() return 1; } - else - { - throw std::move(e); - } + + throw std::move(e); }; StreamingFormatExecutor executor(non_virtual_header, input_format, on_error); diff --git a/src/Storages/FileLog/StorageFileLog.cpp b/src/Storages/FileLog/StorageFileLog.cpp index 38e65766b52..5642e8ea486 100644 --- a/src/Storages/FileLog/StorageFileLog.cpp +++ b/src/Storages/FileLog/StorageFileLog.cpp @@ -165,11 +165,8 @@ StorageFileLog::StorageFileLog( LOG_ERROR(log, "The absolute data path should be inside `user_files_path`({})", getContext()->getUserFilesPath()); return; } - else - throw Exception( - ErrorCodes::BAD_ARGUMENTS, - "The absolute data path should be inside `user_files_path`({})", - getContext()->getUserFilesPath()); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, "The absolute data path should be inside `user_files_path`({})", getContext()->getUserFilesPath()); } bool created_metadata_directory = false; @@ -670,10 +667,9 @@ void StorageFileLog::threadFunc() milliseconds_to_wait *= filelog_settings->poll_directory_watch_events_backoff_factor.value; break; } - else - { - milliseconds_to_wait = filelog_settings->poll_directory_watch_events_backoff_init.totalMilliseconds(); - } + + milliseconds_to_wait = filelog_settings->poll_directory_watch_events_backoff_init.totalMilliseconds(); + auto ts = std::chrono::steady_clock::now(); auto duration = std::chrono::duration_cast(ts-start_time); diff --git a/src/Storages/FileLog/StorageFileLog.h b/src/Storages/FileLog/StorageFileLog.h index 6c8dbb98cb8..5ce2a0eae51 100644 --- a/src/Storages/FileLog/StorageFileLog.h +++ b/src/Storages/FileLog/StorageFileLog.h @@ -120,8 +120,7 @@ public: { if (auto it = map.find(key); it != map.end()) return it->second; - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "The key {} doesn't exist.", key); + throw Exception(ErrorCodes::LOGICAL_ERROR, "The key {} doesn't exist.", key); } void increaseStreams(); diff --git a/src/Storages/Hive/HiveCommon.cpp b/src/Storages/Hive/HiveCommon.cpp index b58302f262e..d58e7b535cc 100644 --- a/src/Storages/Hive/HiveCommon.cpp +++ b/src/Storages/Hive/HiveCommon.cpp @@ -190,10 +190,8 @@ void HiveMetastoreClient::HiveTableMetadata::updateIfNeeded(const std::vectorsecond)); - } + + new_partition_infos.emplace(partition.sd.location, std::move(it->second)); } partition_infos.swap(new_partition_infos); diff --git a/src/Storages/Hive/HiveFile.cpp b/src/Storages/Hive/HiveFile.cpp index 9098e20946b..64e47b51a6d 100644 --- a/src/Storages/Hive/HiveFile.cpp +++ b/src/Storages/Hive/HiveFile.cpp @@ -44,18 +44,16 @@ Range createRangeFromOrcStatistics(const StatisticsType * stats) { return Range(FieldType(stats->getMinimum()), true, FieldType(stats->getMaximum()), true); } - else if (stats->hasMinimum()) + if (stats->hasMinimum()) { return Range::createLeftBounded(FieldType(stats->getMinimum()), true); } - else if (stats->hasMaximum()) + if (stats->hasMaximum()) { return Range::createRightBounded(FieldType(stats->getMaximum()), true); } - else - { - return Range::createWholeUniverseWithoutNull(); - } + + return Range::createWholeUniverseWithoutNull(); } template @@ -122,15 +120,15 @@ Range HiveORCFile::buildRange(const orc::ColumnStatistics * col_stats) { return createRangeFromOrcStatistics(int_stats); } - else if (const auto * double_stats = dynamic_cast(col_stats)) + if (const auto * double_stats = dynamic_cast(col_stats)) { return createRangeFromOrcStatistics(double_stats); } - else if (const auto * string_stats = dynamic_cast(col_stats)) + if (const auto * string_stats = dynamic_cast(col_stats)) { return createRangeFromOrcStatistics(string_stats); } - else if (const auto * bool_stats = dynamic_cast(col_stats)) + if (const auto * bool_stats = dynamic_cast(col_stats)) { auto false_cnt = bool_stats->getFalseCount(); auto true_cnt = bool_stats->getTrueCount(); @@ -138,11 +136,11 @@ Range HiveORCFile::buildRange(const orc::ColumnStatistics * col_stats) { return Range(UInt8(0), true, UInt8(1), true); } - else if (false_cnt) + if (false_cnt) { return Range::createLeftBounded(UInt8(0), true); } - else if (true_cnt) + if (true_cnt) { return Range::createRightBounded(UInt8(1), true); } diff --git a/src/Storages/Hive/StorageHive.cpp b/src/Storages/Hive/StorageHive.cpp index dcae5cad985..5d312de8e5d 100644 --- a/src/Storages/Hive/StorageHive.cpp +++ b/src/Storages/Hive/StorageHive.cpp @@ -254,14 +254,13 @@ public: return std::make_unique( getThreadPoolReader(FilesystemReaderType::ASYNCHRONOUS_REMOTE_FS_READER), read_settings, std::move(buf)); } - else - { - return std::make_unique( - hdfs_namenode_url, - current_path, - getContext()->getGlobalContext()->getConfigRef(), - getContext()->getReadSettings()); - } + + return std::make_unique( + hdfs_namenode_url, + current_path, + getContext()->getGlobalContext()->getConfigRef(), + getContext()->getReadSettings()); + }; raw_read_buf = get_raw_read_buf(); @@ -557,13 +556,11 @@ ASTPtr StorageHive::extractKeyExpressionList(const ASTPtr & node) /// Primary key is specified in tuple, extract its arguments. return expr_func->arguments->clone(); } - else - { - /// Primary key consists of one column. - auto res = std::make_shared(); - res->children.push_back(node); - return res; - } + + /// Primary key consists of one column. + auto res = std::make_shared(); + res->children.push_back(node); + return res; } @@ -874,7 +871,7 @@ void StorageHive::read( { if (format_name == "Parquet") return settings[Setting::input_format_parquet_case_insensitive_column_matching]; - else if (format_name == "ORC") + if (format_name == "ORC") return settings[Setting::input_format_orc_case_insensitive_column_matching]; return false; }; diff --git a/src/Storages/IStorage.cpp b/src/Storages/IStorage.cpp index f56b959435c..23f1811d330 100644 --- a/src/Storages/IStorage.cpp +++ b/src/Storages/IStorage.cpp @@ -103,14 +103,13 @@ std::optional IStorage::tryLockForAlter(const std::ch IStorage::AlterLockHolder IStorage::lockForAlter(const std::chrono::milliseconds & acquire_timeout) { - - if (auto lock = tryLockForAlter(acquire_timeout); lock == std::nullopt) + auto lock = tryLockForAlter(acquire_timeout); + if (lock == std::nullopt) throw Exception(ErrorCodes::DEADLOCK_AVOIDED, "Locking attempt for ALTER on \"{}\" has timed out! ({} ms) " "Possible deadlock avoided. Client should retry.", getStorageID().getFullTableName(), acquire_timeout.count()); - else - return std::move(*lock); + return std::move(*lock); } diff --git a/src/Storages/KVStorageUtils.cpp b/src/Storages/KVStorageUtils.cpp index 88783246e10..9731c28fd5a 100644 --- a/src/Storages/KVStorageUtils.cpp +++ b/src/Storages/KVStorageUtils.cpp @@ -42,7 +42,7 @@ bool traverseASTFilter( return true; return false; } - else if (function->name == "or") + if (function->name == "or") { // make sure every child has the key filter condition for (const auto & child : function->arguments->children) @@ -50,7 +50,7 @@ bool traverseASTFilter( return false; return true; } - else if (function->name == "equals" || function->name == "in") + if (function->name == "equals" || function->name == "in") { const auto & args = function->arguments->as(); const ASTIdentifier * ident; @@ -72,7 +72,7 @@ bool traverseASTFilter( return false; value = args.children.at(1); - PreparedSets::Hash set_key = value->getTreeHash(/*ignore_aliases=*/ true); + PreparedSets::Hash set_key = value->getTreeHash(/*ignore_aliases=*/true); FutureSetPtr future_set; if ((value->as() || value->as())) @@ -102,27 +102,25 @@ bool traverseASTFilter( res->push_back(set_column[row]); return true; } + + if ((ident = args.children.at(0)->as())) + value = args.children.at(1); + else if ((ident = args.children.at(1)->as())) + value = args.children.at(0); else + return false; + + if (ident->name() != primary_key) + return false; + + const auto node = evaluateConstantExpressionAsLiteral(value, context); + /// function->name == "equals" + if (const auto * literal = node->as()) { - if ((ident = args.children.at(0)->as())) - value = args.children.at(1); - else if ((ident = args.children.at(1)->as())) - value = args.children.at(0); - else - return false; - - if (ident->name() != primary_key) - return false; - - const auto node = evaluateConstantExpressionAsLiteral(value, context); - /// function->name == "equals" - if (const auto * literal = node->as()) - { - auto converted_field = convertFieldToType(literal->value, *primary_key_type); - if (!converted_field.isNull()) - res->push_back(converted_field); - return true; - } + auto converted_field = convertFieldToType(literal->value, *primary_key_type); + if (!converted_field.isNull()) + res->push_back(converted_field); + return true; } } return false; @@ -147,7 +145,7 @@ bool traverseDAGFilter( return true; return false; } - else if (func_name == "or") + if (func_name == "or") { // make sure every child has the key filter condition for (const auto * child : elem->children) @@ -155,7 +153,7 @@ bool traverseDAGFilter( return false; return true; } - else if (func_name == "equals" || func_name == "in") + if (func_name == "equals" || func_name == "in") { if (elem->children.size() != 2) return false; @@ -204,27 +202,25 @@ bool traverseDAGFilter( res->push_back(set_column[row]); return true; } - else - { - const auto * key = elem->children.at(0); - while (key->type == ActionsDAG::ActionType::ALIAS) - key = key->children.at(0); - if (key->type != ActionsDAG::ActionType::INPUT) - return false; + const auto * key = elem->children.at(0); + while (key->type == ActionsDAG::ActionType::ALIAS) + key = key->children.at(0); - if (key->result_name != primary_key) - return false; + if (key->type != ActionsDAG::ActionType::INPUT) + return false; - const auto * value = elem->children.at(1); - if (value->type != ActionsDAG::ActionType::COLUMN) - return false; + if (key->result_name != primary_key) + return false; - auto converted_field = convertFieldToType((*value->column)[0], *primary_key_type); - if (!converted_field.isNull()) - res->push_back(converted_field); - return true; - } + const auto * value = elem->children.at(1); + if (value->type != ActionsDAG::ActionType::COLUMN) + return false; + + auto converted_field = convertFieldToType((*value->column)[0], *primary_key_type); + if (!converted_field.isNull()) + res->push_back(converted_field); + return true; } return false; } diff --git a/src/Storages/Kafka/KafkaConsumer.cpp b/src/Storages/Kafka/KafkaConsumer.cpp index d9256cf39ce..20d90fae1a1 100644 --- a/src/Storages/Kafka/KafkaConsumer.cpp +++ b/src/Storages/Kafka/KafkaConsumer.cpp @@ -285,11 +285,8 @@ void KafkaConsumer::commit() "All commit attempts failed. Last block was already written to target table(s), " "but was not committed to Kafka."); } - else - { - ProfileEvents::increment(ProfileEvents::KafkaCommits); - } + ProfileEvents::increment(ProfileEvents::KafkaCommits); } else { @@ -420,7 +417,7 @@ ReadBufferPtr KafkaConsumer::consume() { return nullptr; } - else if (stalled_status == REBALANCE_HAPPENED) + if (stalled_status == REBALANCE_HAPPENED) { if (!new_messages.empty()) { @@ -443,32 +440,29 @@ ReadBufferPtr KafkaConsumer::consume() { continue; } - else - { - LOG_WARNING(log, "Can't get assignment. Will keep trying."); - stalled_status = NO_ASSIGNMENT; - return nullptr; - } + + LOG_WARNING(log, "Can't get assignment. Will keep trying."); + stalled_status = NO_ASSIGNMENT; + return nullptr; } - else if (assignment->empty()) + if (assignment->empty()) { LOG_TRACE(log, "Empty assignment."); return nullptr; } - else - { - LOG_TRACE(log, "Stalled"); - return nullptr; - } - } - else - { - messages = std::move(new_messages); - current = messages.begin(); - LOG_TRACE(log, "Polled batch of {} messages. Offsets position: {}", - messages.size(), consumer->get_offsets_position(consumer->get_assignment())); - break; + + LOG_TRACE(log, "Stalled"); + return nullptr; } + + messages = std::move(new_messages); + current = messages.begin(); + LOG_TRACE( + log, + "Polled batch of {} messages. Offsets position: {}", + messages.size(), + consumer->get_offsets_position(consumer->get_assignment())); + break; } filterMessageErrors(); diff --git a/src/Storages/Kafka/KafkaConsumer2.cpp b/src/Storages/Kafka/KafkaConsumer2.cpp index 60626dfa402..4f3d2369328 100644 --- a/src/Storages/Kafka/KafkaConsumer2.cpp +++ b/src/Storages/Kafka/KafkaConsumer2.cpp @@ -255,17 +255,15 @@ ReadBufferPtr KafkaConsumer2::consume(const TopicPartition & topic_partition, co LOG_TRACE(log, "Stalled"); return nullptr; } - else - { - messages = std::move(new_messages); - current = messages.begin(); - LOG_TRACE( - log, - "Polled batch of {} messages. Offsets position: {}", - messages.size(), - consumer->get_offsets_position(consumer->get_assignment())); - break; - } + + messages = std::move(new_messages); + current = messages.begin(); + LOG_TRACE( + log, + "Polled batch of {} messages. Offsets position: {}", + messages.size(), + consumer->get_offsets_position(consumer->get_assignment())); + break; } filterMessageErrors(); diff --git a/src/Storages/Kafka/KafkaSource.cpp b/src/Storages/Kafka/KafkaSource.cpp index a2c87237af6..9e654b9fd94 100644 --- a/src/Storages/Kafka/KafkaSource.cpp +++ b/src/Storages/Kafka/KafkaSource.cpp @@ -135,13 +135,14 @@ Chunk KafkaSource::generateImpl() return 1; } - else - { - e.addMessage("while parsing Kafka message (topic: {}, partition: {}, offset: {})'", - consumer->currentTopic(), consumer->currentPartition(), consumer->currentOffset()); - consumer->setExceptionInfo(e.message()); - throw std::move(e); - } + + e.addMessage( + "while parsing Kafka message (topic: {}, partition: {}, offset: {})'", + consumer->currentTopic(), + consumer->currentPartition(), + consumer->currentOffset()); + consumer->setExceptionInfo(e.message()); + throw std::move(e); }; StreamingFormatExecutor executor(non_virtual_header, input_format, std::move(on_error)); @@ -255,7 +256,7 @@ Chunk KafkaSource::generateImpl() { return {}; } - else if (consumer->polledDataUnusable()) + if (consumer->polledDataUnusable()) { // the rows were counted already before by KafkaRowsRead, // so let's count the rows we ignore separately diff --git a/src/Storages/Kafka/StorageKafka2.cpp b/src/Storages/Kafka/StorageKafka2.cpp index 90cd09fdb92..0d8702d9e47 100644 --- a/src/Storages/Kafka/StorageKafka2.cpp +++ b/src/Storages/Kafka/StorageKafka2.cpp @@ -559,7 +559,7 @@ bool StorageKafka2::createTableIfNotExists() LOG_INFO(log, "It looks like the table {} was created by another replica at the same moment, will retry", keeper_path); continue; } - else if (code != Coordination::Error::ZOK) + if (code != Coordination::Error::ZOK) { zkutil::KeeperMultiException::check(code, ops, responses); } @@ -601,7 +601,7 @@ bool StorageKafka2::removeTableNodesFromZooKeeper(zkutil::ZooKeeperPtr keeper_to throw Exception( ErrorCodes::LOGICAL_ERROR, "There is a race condition between creation and removal of replicated table. It's a bug"); } - else if (code == Coordination::Error::ZNOTEMPTY) + if (code == Coordination::Error::ZNOTEMPTY) { LOG_ERROR( log, @@ -846,15 +846,13 @@ StorageKafka2::PolledBatchInfo StorageKafka2::pollConsumer( return 1; } - else - { - e.addMessage( - "while parsing Kafka message (topic: {}, partition: {}, offset: {})'", - consumer.currentTopic(), - consumer.currentPartition(), - consumer.currentOffset()); - throw std::move(e); - } + + e.addMessage( + "while parsing Kafka message (topic: {}, partition: {}, offset: {})'", + consumer.currentTopic(), + consumer.currentPartition(), + consumer.currentOffset()); + throw std::move(e); }; StreamingFormatExecutor executor(non_virtual_header, input_format, std::move(on_error)); diff --git a/src/Storages/Kafka/StorageKafkaUtils.cpp b/src/Storages/Kafka/StorageKafkaUtils.cpp index 7c23d1ab2f6..19a6dbc3a7f 100644 --- a/src/Storages/Kafka/StorageKafkaUtils.cpp +++ b/src/Storages/Kafka/StorageKafkaUtils.cpp @@ -104,7 +104,6 @@ void registerStorageKafka(StorageFactory & factory) { \ /* The same argument is given in two places */ \ if (has_settings && kafka_settings->PAR_NAME.changed) \ - { \ throw Exception( \ ErrorCodes::BAD_ARGUMENTS, \ "The argument â„–{} of storage Kafka " \ @@ -112,21 +111,17 @@ void registerStorageKafka(StorageFactory & factory) "in SETTINGS cannot be specified at the same time", \ #ARG_NUM, \ #PAR_NAME); \ - } \ /* move engine args to settings */ \ - else \ + if constexpr ((EVAL) == 1) \ { \ - if constexpr ((EVAL) == 1) \ - { \ - engine_args[(ARG_NUM)-1] = evaluateConstantExpressionAsLiteral(engine_args[(ARG_NUM)-1], args.getLocalContext()); \ - } \ - if constexpr ((EVAL) == 2) \ - { \ - engine_args[(ARG_NUM)-1] \ - = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[(ARG_NUM)-1], args.getLocalContext()); \ - } \ - kafka_settings->PAR_NAME = engine_args[(ARG_NUM)-1]->as().value; \ + engine_args[(ARG_NUM)-1] = evaluateConstantExpressionAsLiteral(engine_args[(ARG_NUM)-1], args.getLocalContext()); \ } \ + if constexpr ((EVAL) == 2) \ + { \ + engine_args[(ARG_NUM)-1] \ + = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[(ARG_NUM)-1], args.getLocalContext()); \ + } \ + kafka_settings->PAR_NAME = engine_args[(ARG_NUM)-1]->as().value; \ } /** Arguments of engine is following: @@ -185,7 +180,7 @@ void registerStorageKafka(StorageFactory & factory) "See also https://clickhouse.com/docs/integrations/kafka/kafka-table-engine#tuning-performance", max_consumers); } - else if (num_consumers < 1) + if (num_consumers < 1) { throw Exception(ErrorCodes::BAD_ARGUMENTS, "Number of consumers can not be lower than 1"); } @@ -332,11 +327,9 @@ void drainConsumer( { break; } - else - { - LOG_ERROR(log, "Error during draining: {}", error); - error_handler(error); - } + + LOG_ERROR(log, "Error during draining: {}", error); + error_handler(error); } // i don't stop draining on first error, diff --git a/src/Storages/LiveView/LiveViewEventsSource.h b/src/Storages/LiveView/LiveViewEventsSource.h index 4210acbc5bc..6740ee897f0 100644 --- a/src/Storages/LiveView/LiveViewEventsSource.h +++ b/src/Storages/LiveView/LiveViewEventsSource.h @@ -185,12 +185,10 @@ protected: { break; } - else - { - // repeat the event block as a heartbeat - last_event_timestamp_usec = static_cast(timestamp.epochMicroseconds()); - return { getPort().getHeader(), true }; - } + + // repeat the event block as a heartbeat + last_event_timestamp_usec = static_cast(timestamp.epochMicroseconds()); + return {getPort().getHeader(), true}; } } } diff --git a/src/Storages/LiveView/LiveViewSource.h b/src/Storages/LiveView/LiveViewSource.h index 81dd5620e57..fdc07ed0ccf 100644 --- a/src/Storages/LiveView/LiveViewSource.h +++ b/src/Storages/LiveView/LiveViewSource.h @@ -153,12 +153,10 @@ protected: { break; } - else - { - // heartbeat - last_event_timestamp_usec = static_cast(Poco::Timestamp().epochMicroseconds()); - return { getPort().getHeader(), true }; - } + + // heartbeat + last_event_timestamp_usec = static_cast(Poco::Timestamp().epochMicroseconds()); + return {getPort().getHeader(), true}; } } } diff --git a/src/Storages/LiveView/StorageLiveView.cpp b/src/Storages/LiveView/StorageLiveView.cpp index df61df6e586..1f0bdf1a2fc 100644 --- a/src/Storages/LiveView/StorageLiveView.cpp +++ b/src/Storages/LiveView/StorageLiveView.cpp @@ -135,7 +135,7 @@ SelectQueryDescription buildSelectQueryDescription(const ASTPtr & select_query, break; } - else if (auto subquery = extractTableExpression(*inner_select_query, 0)) + if (auto subquery = extractTableExpression(*inner_select_query, 0)) { inner_query = subquery; } diff --git a/src/Storages/MaterializedView/RefreshTask.cpp b/src/Storages/MaterializedView/RefreshTask.cpp index 3b5e88b82cf..edfd62c621e 100644 --- a/src/Storages/MaterializedView/RefreshTask.cpp +++ b/src/Storages/MaterializedView/RefreshTask.cpp @@ -879,8 +879,7 @@ std::chrono::system_clock::time_point RefreshTask::currentTime() const Int64 fake = scheduling.fake_clock.load(std::memory_order::relaxed); if (fake == INT64_MIN) return std::chrono::system_clock::now(); - else - return std::chrono::system_clock::time_point(std::chrono::seconds(fake)); + return std::chrono::system_clock::time_point(std::chrono::seconds(fake)); } void RefreshTask::setRefreshSetHandleUnlock(RefreshSet::Handle && set_handle_) diff --git a/src/Storages/MergeTree/AllMergeSelector.cpp b/src/Storages/MergeTree/AllMergeSelector.cpp index 5e406c6e4f7..1bd73de6884 100644 --- a/src/Storages/MergeTree/AllMergeSelector.cpp +++ b/src/Storages/MergeTree/AllMergeSelector.cpp @@ -31,8 +31,7 @@ AllMergeSelector::PartsRange AllMergeSelector::select( if (min_partition_size) return *best_partition; - else - return {}; + return {}; } } diff --git a/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp b/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp index 797e3a32084..fd0fa38138f 100644 --- a/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp +++ b/src/Storages/MergeTree/DataPartStorageOnDiskBase.cpp @@ -427,7 +427,7 @@ void DataPartStorageOnDiskBase::backup( backup_entries.emplace_back(filepath_in_backup, std::make_unique(disk, filepath_on_disk, read_settings, copy_encrypted)); return; } - else if (is_projection_part && allow_backup_broken_projection && !disk->exists(filepath_on_disk)) + if (is_projection_part && allow_backup_broken_projection && !disk->exists(filepath_on_disk)) return; if (make_temporary_hard_links) diff --git a/src/Storages/MergeTree/DataPartStorageOnDiskFull.cpp b/src/Storages/MergeTree/DataPartStorageOnDiskFull.cpp index b3dc9ad16d4..42f82fd96e2 100644 --- a/src/Storages/MergeTree/DataPartStorageOnDiskFull.cpp +++ b/src/Storages/MergeTree/DataPartStorageOnDiskFull.cpp @@ -136,8 +136,7 @@ std::unique_ptr DataPartStorageOnDiskFull::writeFile( { if (transaction) return transaction->writeFile(fs::path(root_path) / part_dir / name, buf_size, mode, settings, /* autocommit = */ false); - else - return volume->getDisk()->writeFile(fs::path(root_path) / part_dir / name, buf_size, mode, settings); + return volume->getDisk()->writeFile(fs::path(root_path) / part_dir / name, buf_size, mode, settings); } void DataPartStorageOnDiskFull::createFile(const String & name) diff --git a/src/Storages/MergeTree/EphemeralLockInZooKeeper.cpp b/src/Storages/MergeTree/EphemeralLockInZooKeeper.cpp index cbdeabffa97..57810b1e35e 100644 --- a/src/Storages/MergeTree/EphemeralLockInZooKeeper.cpp +++ b/src/Storages/MergeTree/EphemeralLockInZooKeeper.cpp @@ -171,7 +171,7 @@ EphemeralLocksInAllPartitions::EphemeralLocksInAllPartitions( LOG_TRACE(getLogger("EphemeralLocksInAllPartitions"), "Someone has inserted a block in a new partition while we were creating locks. Retry."); continue; } - else if (rc != Coordination::Error::ZOK) + if (rc != Coordination::Error::ZOK) throw Coordination::Exception(rc); for (size_t i = 0; i < partitions.size(); ++i) diff --git a/src/Storages/MergeTree/GinIndexStore.cpp b/src/Storages/MergeTree/GinIndexStore.cpp index e92460ff498..5684df68ee4 100644 --- a/src/Storages/MergeTree/GinIndexStore.cpp +++ b/src/Storages/MergeTree/GinIndexStore.cpp @@ -36,11 +36,9 @@ bool GinIndexPostingsBuilder::contains(UInt32 row_id) const { if (useRoaring()) return rowid_bitmap.contains(row_id); - else - { - const auto * const it = std::find(rowid_lst.begin(), rowid_lst.begin()+rowid_lst_length, row_id); - return it != rowid_lst.begin() + rowid_lst_length; - } + + const auto * const it = std::find(rowid_lst.begin(), rowid_lst.begin() + rowid_lst_length, row_id); + return it != rowid_lst.begin() + rowid_lst_length; } void GinIndexPostingsBuilder::add(UInt32 row_id) @@ -137,17 +135,15 @@ GinIndexPostingsListPtr GinIndexPostingsBuilder::deserialize(ReadBuffer & buffer return postings_list; } - else - { - assert(postings_list_size < MIN_SIZE_FOR_ROARING_ENCODING); - GinIndexPostingsListPtr postings_list = std::make_shared(); - UInt32 row_ids[MIN_SIZE_FOR_ROARING_ENCODING]; - for (auto i = 0; i < postings_list_size; ++i) - readVarUInt(row_ids[i], buffer); - postings_list->addMany(postings_list_size, row_ids); - return postings_list; - } + assert(postings_list_size < MIN_SIZE_FOR_ROARING_ENCODING); + GinIndexPostingsListPtr postings_list = std::make_shared(); + UInt32 row_ids[MIN_SIZE_FOR_ROARING_ENCODING]; + + for (auto i = 0; i < postings_list_size; ++i) + readVarUInt(row_ids[i], buffer); + postings_list->addMany(postings_list_size, row_ids); + return postings_list; } GinIndexStore::GinIndexStore(const String & name_, DataPartStoragePtr storage_) diff --git a/src/Storages/MergeTree/IMergeTreeDataPart.cpp b/src/Storages/MergeTree/IMergeTreeDataPart.cpp index 484e544f921..4bdee6701d6 100644 --- a/src/Storages/MergeTree/IMergeTreeDataPart.cpp +++ b/src/Storages/MergeTree/IMergeTreeDataPart.cpp @@ -413,8 +413,7 @@ String IMergeTreeDataPart::getNewName(const MergeTreePartInfo & new_part_info) c MergeTreePartInfo::parseMinMaxDatesFromPartName(name, min_date, max_date); return new_part_info.getPartNameV0(min_date, max_date); } - else - return new_part_info.getPartNameV1(); + return new_part_info.getPartNameV1(); } std::optional IMergeTreeDataPart::getColumnPosition(const String & column_name) const @@ -441,8 +440,7 @@ std::pair IMergeTreeDataPart::getMinMaxDate() const const auto & hyperrectangle = minmax_idx->hyperrectangle[storage.minmax_idx_date_column_pos]; return {DayNum(hyperrectangle.left.safeGet()), DayNum(hyperrectangle.right.safeGet())}; } - else - return {}; + return {}; } std::pair IMergeTreeDataPart::getMinMaxTime() const @@ -458,7 +456,7 @@ std::pair IMergeTreeDataPart::getMinMaxTime() const return {hyperrectangle.left.safeGet(), hyperrectangle.right.safeGet()}; } /// The case of DateTime64 - else if (hyperrectangle.left.getType() == Field::Types::Decimal64) + if (hyperrectangle.left.getType() == Field::Types::Decimal64) { assert(hyperrectangle.right.getType() == Field::Types::Decimal64); @@ -467,13 +465,11 @@ std::pair IMergeTreeDataPart::getMinMaxTime() const assert(left.getScale() == right.getScale()); - return { left.getValue() / left.getScaleMultiplier(), right.getValue() / right.getScaleMultiplier() }; + return {left.getValue() / left.getScaleMultiplier(), right.getValue() / right.getScaleMultiplier()}; } - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Part minmax index by time is neither DateTime or DateTime64"); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Part minmax index by time is neither DateTime or DateTime64"); } - else - return {}; + return {}; } @@ -651,8 +647,7 @@ UInt64 IMergeTreeDataPart::getExistingBytesOnDisk() const if ((*storage.getSettings())[MergeTreeSetting::exclude_deleted_rows_for_part_size_in_merge] && supportLightweightDeleteMutate() && hasLightweightDelete() && existing_rows_count.has_value() && existing_rows_count.value() < rows_count && rows_count > 0) return bytes_on_disk * existing_rows_count.value() / rows_count; - else - return bytes_on_disk; + return bytes_on_disk; } size_t IMergeTreeDataPart::getFileSizeOrZero(const String & file_name) const @@ -2346,7 +2341,7 @@ bool IMergeTreeDataPart::checkAllTTLCalculated(const StorageMetadataPtr & metada { if (isEmpty()) /// All rows were finally deleted and we don't store TTL return true; - else if (ttl_infos.table_ttl.min == 0) + if (ttl_infos.table_ttl.min == 0) return false; } diff --git a/src/Storages/MergeTree/IMergeTreeDataPartWriter.cpp b/src/Storages/MergeTree/IMergeTreeDataPartWriter.cpp index 4f42a7e9122..3d6366f9217 100644 --- a/src/Storages/MergeTree/IMergeTreeDataPartWriter.cpp +++ b/src/Storages/MergeTree/IMergeTreeDataPartWriter.cpp @@ -181,12 +181,24 @@ MergeTreeDataPartWriterPtr createMergeTreeDataPartWriter( return createMergeTreeDataPartCompactWriter(data_part_name_, logger_name_, serializations_, data_part_storage_, index_granularity_info_, storage_settings_, columns_list, column_positions, metadata_snapshot, virtual_columns, indices_to_recalc, stats_to_recalc_, marks_file_extension_, default_codec_, writer_settings, computed_index_granularity); - else if (part_type == MergeTreeDataPartType::Wide) - return createMergeTreeDataPartWideWriter(data_part_name_, logger_name_, serializations_, data_part_storage_, - index_granularity_info_, storage_settings_, columns_list, metadata_snapshot, virtual_columns, indices_to_recalc, stats_to_recalc_, - marks_file_extension_, default_codec_, writer_settings, computed_index_granularity); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown part type: {}", part_type.toString()); + if (part_type == MergeTreeDataPartType::Wide) + return createMergeTreeDataPartWideWriter( + data_part_name_, + logger_name_, + serializations_, + data_part_storage_, + index_granularity_info_, + storage_settings_, + columns_list, + metadata_snapshot, + virtual_columns, + indices_to_recalc, + stats_to_recalc_, + marks_file_extension_, + default_codec_, + writer_settings, + computed_index_granularity); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown part type: {}", part_type.toString()); } } diff --git a/src/Storages/MergeTree/KeyCondition.cpp b/src/Storages/MergeTree/KeyCondition.cpp index da05cdb2206..2a3a283bc7d 100644 --- a/src/Storages/MergeTree/KeyCondition.cpp +++ b/src/Storages/MergeTree/KeyCondition.cpp @@ -1058,13 +1058,12 @@ bool KeyCondition::canConstantBeWrappedByMonotonicFunctions( { if (!func.hasInformationAboutMonotonicity()) return false; - else - { - /// Range is irrelevant in this case. - auto monotonicity = func.getMonotonicityForRange(type, Field(), Field()); - if (!monotonicity.is_always_monotonic) - return false; - } + + /// Range is irrelevant in this case. + auto monotonicity = func.getMonotonicityForRange(type, Field(), Field()); + if (!monotonicity.is_always_monotonic) + return false; + return true; }); @@ -1427,15 +1426,14 @@ public: new_arguments.push_back(arg); return func->prepare(new_arguments)->execute(new_arguments, result_type, input_rows_count, dry_run); } - else if (kind == Kind::RIGHT_CONST) + if (kind == Kind::RIGHT_CONST) { auto new_arguments = arguments; new_arguments.push_back(const_arg); new_arguments.back().column = new_arguments.back().column->cloneResized(input_rows_count); return func->prepare(new_arguments)->execute(new_arguments, result_type, input_rows_count, dry_run); } - else - return func->prepare(arguments)->execute(arguments, result_type, input_rows_count, dry_run); + return func->prepare(arguments)->execute(arguments, result_type, input_rows_count, dry_run); } bool isDeterministic() const override { return func->isDeterministic(); } @@ -2118,8 +2116,8 @@ bool KeyCondition::extractAtomFromTree(const RPNBuilderTreeNode & node, RPNEleme /// Case2 has holes in polygon, when checking skip index, the hole will be ignored. return analyze_point_in_polygon(); } - else - return false; + + return false; } const auto atom_it = atom_map.find(func_name); @@ -2130,7 +2128,7 @@ bool KeyCondition::extractAtomFromTree(const RPNBuilderTreeNode & node, RPNEleme return atom_it->second(out, const_value); } - else if (node.tryGetConstant(const_value, const_type)) + if (node.tryGetConstant(const_value, const_type)) { /// For cases where it says, for example, `WHERE 0 AND something` @@ -2139,12 +2137,12 @@ bool KeyCondition::extractAtomFromTree(const RPNBuilderTreeNode & node, RPNEleme out.function = const_value.safeGet() ? RPNElement::ALWAYS_TRUE : RPNElement::ALWAYS_FALSE; return true; } - else if (const_value.getType() == Field::Types::Int64) + if (const_value.getType() == Field::Types::Int64) { out.function = const_value.safeGet() ? RPNElement::ALWAYS_TRUE : RPNElement::ALWAYS_FALSE; return true; } - else if (const_value.getType() == Field::Types::Float64) + if (const_value.getType() == Field::Types::Float64) { out.function = const_value.safeGet() != 0.0 ? RPNElement::ALWAYS_TRUE : RPNElement::ALWAYS_FALSE; return true; @@ -2204,7 +2202,7 @@ void KeyCondition::findHyperrectanglesForArgumentsOfSpaceFillingCurves() new_rpn.push_back(std::move(collapsed_elem)); continue; } - else if (elem.function == RPNElement::FUNCTION_AND && new_rpn.size() >= 2) + if (elem.function == RPNElement::FUNCTION_AND && new_rpn.size() >= 2) { /// AND of two conditions @@ -2213,18 +2211,16 @@ void KeyCondition::findHyperrectanglesForArgumentsOfSpaceFillingCurves() /// Related to the same column of the key, represented by a space-filling curve - if (cond1.key_column == cond2.key_column - && cond1.function == RPNElement::FUNCTION_ARGS_IN_HYPERRECTANGLE + if (cond1.key_column == cond2.key_column && cond1.function == RPNElement::FUNCTION_ARGS_IN_HYPERRECTANGLE && cond2.function == RPNElement::FUNCTION_ARGS_IN_HYPERRECTANGLE) { - /// Intersect these two conditions (applying AND) + /// Intersect these two conditions (applying AND) RPNElement collapsed_elem; collapsed_elem.function = RPNElement::FUNCTION_ARGS_IN_HYPERRECTANGLE; collapsed_elem.key_column = cond1.key_column; - collapsed_elem.space_filling_curve_args_hyperrectangle = intersect( - cond1.space_filling_curve_args_hyperrectangle, - cond2.space_filling_curve_args_hyperrectangle); + collapsed_elem.space_filling_curve_args_hyperrectangle + = intersect(cond1.space_filling_curve_args_hyperrectangle, cond2.space_filling_curve_args_hyperrectangle); /// Replace the AND operation with its arguments to the collapsed condition @@ -3252,17 +3248,16 @@ String KeyCondition::RPNElement::toString() const { if (argument_num_of_space_filling_curve) return toString(fmt::format("argument {} of column {}", *argument_num_of_space_filling_curve, key_column), false); - else if (point_in_polygon_column_description) - { + + if (point_in_polygon_column_description) return toString( fmt::format( "column ({}, {})", point_in_polygon_column_description->key_columns[0], point_in_polygon_column_description->key_columns[1]), false); - } - else - return toString(fmt::format("column {}", key_column), true); + + return toString(fmt::format("column {}", key_column), true); } String KeyCondition::RPNElement::toString(std::string_view column_name, bool print_constants) const diff --git a/src/Storages/MergeTree/LeaderElection.h b/src/Storages/MergeTree/LeaderElection.h index b7dc9c31655..c9d5ba8eff1 100644 --- a/src/Storages/MergeTree/LeaderElection.h +++ b/src/Storages/MergeTree/LeaderElection.h @@ -35,7 +35,7 @@ inline void checkNoOldLeaders(LoggerPtr log, ZooKeeper & zookeeper, const String /// NOTE zookeeper_path/leader_election node must exist now, but maybe we will remove it in future versions. if (code == Coordination::Error::ZNONODE) return; - else if (code != Coordination::Error::ZOK) + if (code != Coordination::Error::ZOK) throw KeeperException::fromPath(code, path); Coordination::Requests ops; @@ -79,7 +79,7 @@ inline void checkNoOldLeaders(LoggerPtr log, ZooKeeper & zookeeper, const String code = zookeeper.tryMulti(ops, res); if (code == Coordination::Error::ZOK) return; - else if (code == Coordination::Error::ZNOTEMPTY || code == Coordination::Error::ZNODEEXISTS || code == Coordination::Error::ZNONODE) + if (code == Coordination::Error::ZNOTEMPTY || code == Coordination::Error::ZNODEEXISTS || code == Coordination::Error::ZNONODE) LOG_INFO(log, "LeaderElection: leader suddenly changed or new node appeared, will retry"); else KeeperMultiException::check(code, ops, res); diff --git a/src/Storages/MergeTree/MergeFromLogEntryTask.cpp b/src/Storages/MergeTree/MergeFromLogEntryTask.cpp index 463349f5b00..56d7133dfc3 100644 --- a/src/Storages/MergeTree/MergeFromLogEntryTask.cpp +++ b/src/Storages/MergeTree/MergeFromLogEntryTask.cpp @@ -292,7 +292,7 @@ ReplicatedMergeMutateTaskBase::PrepareResult MergeFromLogEntryTask::prepare() .part_log_writer = part_log_writer, }; } - else if (storage.findReplicaHavingCoveringPart(entry.new_part_name, /* active */ false)) + if (storage.findReplicaHavingCoveringPart(entry.new_part_name, /* active */ false)) { /// Why this if still needed? We can check for part in zookeeper, don't find it and sleep for any amount of time. During this sleep part will be actually committed from other replica /// and exclusive zero copy lock will be released. We will take the lock and execute merge one more time, while it was possible just to download the part from other replica. @@ -302,17 +302,19 @@ ReplicatedMergeMutateTaskBase::PrepareResult MergeFromLogEntryTask::prepare() /// NOTE: In case of mutation and hardlinks it can even lead to extremely rare dataloss (we will produce new part with the same hardlinks, don't fetch the same from other replica), so this check is important. zero_copy_lock->lock->unlock(); - LOG_DEBUG(log, "We took zero copy lock, but merge of part {} finished by some other replica, will release lock and download merged part to avoid data duplication", entry.new_part_name); + LOG_DEBUG( + log, + "We took zero copy lock, but merge of part {} finished by some other replica, will release lock and download merged " + "part to avoid data duplication", + entry.new_part_name); return PrepareResult{ .prepared_successfully = false, .need_to_check_missing_part_in_fetch = true, .part_log_writer = part_log_writer, }; } - else - { - LOG_DEBUG(log, "Zero copy lock taken, will merge part {}", entry.new_part_name); - } + + LOG_DEBUG(log, "Zero copy lock taken, will merge part {}", entry.new_part_name); } } diff --git a/src/Storages/MergeTree/MergeProjectionPartsTask.cpp b/src/Storages/MergeTree/MergeProjectionPartsTask.cpp index bdc2ba8b9ca..4e1bb2f11a7 100644 --- a/src/Storages/MergeTree/MergeProjectionPartsTask.cpp +++ b/src/Storages/MergeTree/MergeProjectionPartsTask.cpp @@ -43,11 +43,9 @@ bool MergeProjectionPartsTask::executeStep() /// Task is finished return false; } - else - { - LOG_DEBUG(log, "Forwarded part {} in level {} to next level", selected_parts[0]->name, current_level); - next_level_parts.push_back(std::move(selected_parts[0])); - } + + LOG_DEBUG(log, "Forwarded part {} in level {} to next level", selected_parts[0]->name, current_level); + next_level_parts.push_back(std::move(selected_parts[0])); } else if (selected_parts.size() > 1) { diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp index 3dbb9d64f2f..7ba358d2d35 100644 --- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp +++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp @@ -172,7 +172,7 @@ void MergeTreeBlockSizePredictor::initialize(const Block & sample_block, const C { size_t size_of_value = column_data->sizeOfValueIfFixed(); fixed_columns_bytes_per_row += column_data->sizeOfValueIfFixed(); - max_size_per_row_fixed = std::max(max_size_per_row_fixed, size_of_value); + max_size_per_row_fixed = std::max(max_size_per_row_fixed, size_of_value); } else { diff --git a/src/Storages/MergeTree/MergeTreeBlockReadUtils.h b/src/Storages/MergeTree/MergeTreeBlockReadUtils.h index c1514416301..3d18a2fb732 100644 --- a/src/Storages/MergeTree/MergeTreeBlockReadUtils.h +++ b/src/Storages/MergeTree/MergeTreeBlockReadUtils.h @@ -3,6 +3,8 @@ #include #include +#include + namespace DB { @@ -49,7 +51,8 @@ struct MergeTreeBlockSizePredictor /// Predicts what number of rows should be read to exhaust byte quota per column size_t estimateNumRowsForMaxSizeColumn(size_t bytes_quota) const { - double max_size_per_row = std::max(std::max(max_size_per_row_fixed, 1), max_size_per_row_dynamic); + double max_size_per_row + = std::max({max_size_per_row_fixed, static_cast(static_cast(1)), max_size_per_row_dynamic}); return (bytes_quota > block_size_rows * max_size_per_row) ? static_cast(bytes_quota / max_size_per_row) - block_size_rows : 0; @@ -92,7 +95,7 @@ protected: std::vector dynamic_columns_infos; size_t fixed_columns_bytes_per_row = 0; - size_t max_size_per_row_fixed = 0; + double max_size_per_row_fixed = 0; double max_size_per_row_dynamic = 0; size_t number_of_rows_in_part; diff --git a/src/Storages/MergeTree/MergeTreeData.cpp b/src/Storages/MergeTree/MergeTreeData.cpp index 58847817ea9..f1cb750d4ad 100644 --- a/src/Storages/MergeTree/MergeTreeData.cpp +++ b/src/Storages/MergeTree/MergeTreeData.cpp @@ -942,9 +942,8 @@ void MergeTreeData::checkTTLExpressions(const StorageInMemoryMetadata & new_meta if (move_ttl.destination_type == DataDestinationType::DISK) throw Exception(ErrorCodes::BAD_TTL_EXPRESSION, "No such disk {} for given storage policy", backQuote(move_ttl.destination_name)); - else - throw Exception(ErrorCodes::BAD_TTL_EXPRESSION, - "No such volume {} for given storage policy", backQuote(move_ttl.destination_name)); + throw Exception( + ErrorCodes::BAD_TTL_EXPRESSION, "No such volume {} for given storage policy", backQuote(move_ttl.destination_name)); } } } @@ -1089,28 +1088,35 @@ void MergeTreeData::MergingParams::check(const StorageInMemoryMetadata & metadat throw Exception(ErrorCodes::LOGICAL_ERROR, "`is_deleted` ({}) column for storage {} is empty", is_deleted_column, storage); } - else + + if (version_column.empty() && !is_optional) + throw Exception( + ErrorCodes::LOGICAL_ERROR, + "Version column ({}) for storage {} is empty while is_deleted ({}) is not.", + version_column, + storage, + is_deleted_column); + + bool miss_is_deleted_column = true; + for (const auto & column : columns) { - if (version_column.empty() && !is_optional) - throw Exception(ErrorCodes::LOGICAL_ERROR, "Version column ({}) for storage {} is empty while is_deleted ({}) is not.", - version_column, storage, is_deleted_column); - - bool miss_is_deleted_column = true; - for (const auto & column : columns) + if (column.name == is_deleted_column) { - if (column.name == is_deleted_column) - { - if (!typeid_cast(column.type.get())) - throw Exception(ErrorCodes::BAD_TYPE_OF_FIELD, "is_deleted column ({}) for storage {} must have type UInt8. Provided column of type {}.", - is_deleted_column, storage, column.type->getName()); - miss_is_deleted_column = false; - break; - } + if (!typeid_cast(column.type.get())) + throw Exception( + ErrorCodes::BAD_TYPE_OF_FIELD, + "is_deleted column ({}) for storage {} must have type UInt8. Provided column of type {}.", + is_deleted_column, + storage, + column.type->getName()); + miss_is_deleted_column = false; + break; } - - if (miss_is_deleted_column) - throw Exception(ErrorCodes::NO_SUCH_COLUMN_IN_TABLE, "is_deleted column {} does not exist in table declaration.", is_deleted_column); } + + if (miss_is_deleted_column) + throw Exception( + ErrorCodes::NO_SUCH_COLUMN_IN_TABLE, "is_deleted column {} does not exist in table declaration.", is_deleted_column); }; @@ -1306,11 +1312,13 @@ void MergeTreeData::PartLoadingTree::add(const MergeTreePartInfo & info, const S current = prev->second.get(); continue; } - else if (!prev_info.isDisjoint(info)) + if (!prev_info.isDisjoint(info)) { - throw Exception(ErrorCodes::LOGICAL_ERROR, + throw Exception( + ErrorCodes::LOGICAL_ERROR, "Part {} intersects previous part {}. It is a bug or a result of manual intervention in the server or ZooKeeper data", - name, prev->second->name); + name, + prev->second->name); } } @@ -1323,11 +1331,13 @@ void MergeTreeData::PartLoadingTree::add(const MergeTreePartInfo & info, const S current = it->second.get(); continue; } - else if (!next_info.isDisjoint(info)) + if (!next_info.isDisjoint(info)) { - throw Exception(ErrorCodes::LOGICAL_ERROR, + throw Exception( + ErrorCodes::LOGICAL_ERROR, "Part {} intersects next part {}. It is a bug or a result of manual intervention in the server or ZooKeeper data", - name, it->second->name); + name, + it->second->name); } } @@ -1626,8 +1636,7 @@ MergeTreeData::LoadPartResult MergeTreeData::loadDataPart( res.part->is_duplicate = true; return res; } - else - throw Exception(ErrorCodes::DUPLICATE_DATA_PART, "Part {} already exists but with different checksums", res.part->name); + throw Exception(ErrorCodes::DUPLICATE_DATA_PART, "Part {} already exists but with different checksums", res.part->name); } if (to_state == DataPartState::Active) @@ -2419,14 +2428,27 @@ size_t MergeTreeData::clearOldTemporaryDirectories(const String & root_path, siz LOG_INFO(LogFrequencyLimiter(log.load(), 10), "{} is in use (by merge/mutation/INSERT) (consider increasing temporary_directories_lifetime setting)", full_path); continue; } - else if (!disk->exists(it->path())) + if (!disk->exists(it->path())) { /// We should recheck that the dir exists, otherwise we can get "No such file or directory" /// due to a race condition with "Renaming temporary part" (temporary part holder could be already released, so the check above is not enough) - LOG_WARNING(log, "Temporary directory {} suddenly disappeared while iterating, assuming it was concurrently renamed to persistent", it->path()); + LOG_WARNING( + log, + "Temporary directory {} suddenly disappeared while iterating, assuming it was concurrently renamed to " + "persistent", + it->path()); continue; } - else + + LOG_WARNING(log, "Removing temporary directory {}", full_path); + + /// Even if it's a temporary part it could be downloaded with zero copy replication and this function + /// is executed as a callback. + /// + /// We don't control the amount of refs for temporary parts so we cannot decide can we remove blobs + /// or not. So we are not doing it + bool keep_shared = false; + if (disk->supportZeroCopyReplication() && settings->allow_remote_fs_zero_copy_replication && supportsReplication()) { LOG_WARNING(log, "Removing temporary directory {}", full_path); @@ -2445,6 +2467,9 @@ size_t MergeTreeData::clearOldTemporaryDirectories(const String & root_path, siz disk->removeSharedRecursive(it->path(), keep_shared, {}); ++cleared_count; } + + disk->removeSharedRecursive(it->path(), keep_shared, {}); + ++cleared_count; } } catch (const fs::filesystem_error & e) @@ -3425,15 +3450,19 @@ void MergeTreeData::checkAlterIsPossible(const AlterCommands & commands, Context /// No other checks required continue; } - else if (command.type == AlterCommand::DROP_COLUMN) + if (command.type == AlterCommand::DROP_COLUMN) { - throw Exception(ErrorCodes::ALTER_OF_COLUMN_IS_FORBIDDEN, - "Trying to ALTER DROP version {} column", backQuoteIfNeed(command.column_name)); + throw Exception( + ErrorCodes::ALTER_OF_COLUMN_IS_FORBIDDEN, + "Trying to ALTER DROP version {} column", + backQuoteIfNeed(command.column_name)); } - else if (command.type == AlterCommand::RENAME_COLUMN) + if (command.type == AlterCommand::RENAME_COLUMN) { - throw Exception(ErrorCodes::ALTER_OF_COLUMN_IS_FORBIDDEN, - "Trying to ALTER RENAME version {} column", backQuoteIfNeed(command.column_name)); + throw Exception( + ErrorCodes::ALTER_OF_COLUMN_IS_FORBIDDEN, + "Trying to ALTER RENAME version {} column", + backQuoteIfNeed(command.column_name)); } } else if (command.column_name == merging_params.is_deleted_column) @@ -5210,8 +5239,7 @@ void MergeTreeData::movePartitionToDisk(const ASTPtr & partition, const String & { if (moving_part) throw Exception(ErrorCodes::UNKNOWN_DISK, "Part '{}' is already on disk '{}'", partition_id, disk->getName()); - else - throw Exception(ErrorCodes::UNKNOWN_DISK, "All parts of partition '{}' are already on disk '{}'", partition_id, disk->getName()); + throw Exception(ErrorCodes::UNKNOWN_DISK, "All parts of partition '{}' are already on disk '{}'", partition_id, disk->getName()); } if (parts_mover.moves_blocker.isCancelled()) @@ -5232,22 +5260,25 @@ void MergeTreeData::movePartitionToDisk(const ASTPtr & partition, const String & { return; } - else + + auto moves_outcome = moves_future.get(); + switch (moves_outcome) { - auto moves_outcome = moves_future.get(); - switch (moves_outcome) - { - case MovePartsOutcome::MovesAreCancelled: - throw Exception(ErrorCodes::ABORTED, "Cannot move parts because moves are manually disabled"); - case MovePartsOutcome::NothingToMove: - throw Exception(ErrorCodes::NO_SUCH_DATA_PART, "No parts to move are found in partition {}", partition_id); - case MovePartsOutcome::MoveWasPostponedBecauseOfZeroCopy: - throw Exception(ErrorCodes::PART_IS_TEMPORARILY_LOCKED, "Move was not finished, because zero copy mode is enabled and someone other is moving the same parts right now"); - case MovePartsOutcome::CannotScheduleMove: - throw Exception(ErrorCodes::CANNOT_SCHEDULE_TASK, "Cannot schedule move, no free threads, try to wait until all in-progress move finish or increase "); - case MovePartsOutcome::PartsMoved: - break; - } + case MovePartsOutcome::MovesAreCancelled: + throw Exception(ErrorCodes::ABORTED, "Cannot move parts because moves are manually disabled"); + case MovePartsOutcome::NothingToMove: + throw Exception(ErrorCodes::NO_SUCH_DATA_PART, "No parts to move are found in partition {}", partition_id); + case MovePartsOutcome::MoveWasPostponedBecauseOfZeroCopy: + throw Exception( + ErrorCodes::PART_IS_TEMPORARILY_LOCKED, + "Move was not finished, because zero copy mode is enabled and someone other is moving the same parts right now"); + case MovePartsOutcome::CannotScheduleMove: + throw Exception( + ErrorCodes::CANNOT_SCHEDULE_TASK, + "Cannot schedule move, no free threads, try to wait until all in-progress move finish or increase " + ""); + case MovePartsOutcome::PartsMoved: + break; } } @@ -5295,8 +5326,8 @@ void MergeTreeData::movePartitionToVolume(const ASTPtr & partition, const String { if (moving_part) throw Exception(ErrorCodes::UNKNOWN_DISK, "Part '{}' is already on volume '{}'", partition_id, volume->getName()); - else - throw Exception(ErrorCodes::UNKNOWN_DISK, "All parts of partition '{}' are already on volume '{}'", partition_id, volume->getName()); + throw Exception( + ErrorCodes::UNKNOWN_DISK, "All parts of partition '{}' are already on volume '{}'", partition_id, volume->getName()); } if (parts_mover.moves_blocker.isCancelled()) @@ -5317,22 +5348,25 @@ void MergeTreeData::movePartitionToVolume(const ASTPtr & partition, const String { return; } - else + + auto moves_outcome = moves_future.get(); + switch (moves_outcome) { - auto moves_outcome = moves_future.get(); - switch (moves_outcome) - { - case MovePartsOutcome::MovesAreCancelled: - throw Exception(ErrorCodes::ABORTED, "Cannot move parts because moves are manually disabled"); - case MovePartsOutcome::NothingToMove: - throw Exception(ErrorCodes::NO_SUCH_DATA_PART, "No parts to move are found in partition {}", partition_id); - case MovePartsOutcome::MoveWasPostponedBecauseOfZeroCopy: - throw Exception(ErrorCodes::PART_IS_TEMPORARILY_LOCKED, "Move was not finished, because zero copy mode is enabled and someone other is moving the same parts right now"); - case MovePartsOutcome::CannotScheduleMove: - throw Exception(ErrorCodes::CANNOT_SCHEDULE_TASK, "Cannot schedule move, no free threads, try to wait until all in-progress move finish or increase "); - case MovePartsOutcome::PartsMoved: - break; - } + case MovePartsOutcome::MovesAreCancelled: + throw Exception(ErrorCodes::ABORTED, "Cannot move parts because moves are manually disabled"); + case MovePartsOutcome::NothingToMove: + throw Exception(ErrorCodes::NO_SUCH_DATA_PART, "No parts to move are found in partition {}", partition_id); + case MovePartsOutcome::MoveWasPostponedBecauseOfZeroCopy: + throw Exception( + ErrorCodes::PART_IS_TEMPORARILY_LOCKED, + "Move was not finished, because zero copy mode is enabled and someone other is moving the same parts right now"); + case MovePartsOutcome::CannotScheduleMove: + throw Exception( + ErrorCodes::CANNOT_SCHEDULE_TASK, + "Cannot schedule move, no free threads, try to wait until all in-progress move finish or increase " + ""); + case MovePartsOutcome::PartsMoved: + break; } } @@ -6613,21 +6647,19 @@ ReservationPtr MergeTreeData::tryReserveSpacePreferringTTLRules( { return reservation; } - else - { - if (move_ttl_entry->destination_type == DataDestinationType::VOLUME) - LOG_WARNING( - log, - "Would like to reserve space on volume '{}' by TTL rule of table '{}' but there is not enough space", - move_ttl_entry->destination_name, - log.loadName()); - else if (move_ttl_entry->destination_type == DataDestinationType::DISK) - LOG_WARNING( - log, - "Would like to reserve space on disk '{}' by TTL rule of table '{}' but there is not enough space", - move_ttl_entry->destination_name, - log.loadName()); - } + + if (move_ttl_entry->destination_type == DataDestinationType::VOLUME) + LOG_WARNING( + log, + "Would like to reserve space on volume '{}' by TTL rule of table '{}' but there is not enough space", + move_ttl_entry->destination_name, + log.loadName()); + else if (move_ttl_entry->destination_type == DataDestinationType::DISK) + LOG_WARNING( + log, + "Would like to reserve space on disk '{}' by TTL rule of table '{}' but there is not enough space", + move_ttl_entry->destination_name, + log.loadName()); } } @@ -6657,10 +6689,9 @@ SpacePtr MergeTreeData::getDestinationForMoveTTL(const TTLDescription & move_ttl auto policy = getStoragePolicy(); if (move_ttl.destination_type == DataDestinationType::VOLUME) return policy->tryGetVolumeByName(move_ttl.destination_name); - else if (move_ttl.destination_type == DataDestinationType::DISK) + if (move_ttl.destination_type == DataDestinationType::DISK) return policy->tryGetDiskByName(move_ttl.destination_name); - else - return {}; + return {}; } bool MergeTreeData::shouldPerformTTLMoveOnInsert(const SpacePtr & move_destination) const @@ -7705,8 +7736,7 @@ MergeTreeData::MatcherFn MergeTreeData::getPartitionMatcher(const ASTPtr & parti { if (prefixed) return startsWith(partition_id, id); - else - return id == partition_id; + return id == partition_id; }; } @@ -8157,13 +8187,15 @@ MovePartsOutcome MergeTreeData::moveParts(const CurrentlyMovingPartsTaggerPtr & parts_mover.swapClonedPart(cloned_part); break; } - else if (wait_for_move_if_zero_copy) + if (wait_for_move_if_zero_copy) { - LOG_DEBUG(log, "Other replica is working on move of {}, will wait until lock disappear", moving_part.part->name); + LOG_DEBUG( + log, "Other replica is working on move of {}, will wait until lock disappear", moving_part.part->name); /// Wait and checks not only for timeout but also for shutdown and so on. while (!waitZeroCopyLockToDisappear(*lock, 3000)) { - LOG_DEBUG(log, "Waiting until some replica will move {} and zero copy lock disappear", moving_part.part->name); + LOG_DEBUG( + log, "Waiting until some replica will move {} and zero copy lock disappear", moving_part.part->name); } } else diff --git a/src/Storages/MergeTree/MergeTreeDataPartBuilder.cpp b/src/Storages/MergeTree/MergeTreeDataPartBuilder.cpp index 146c15bbb69..37f578b0c25 100644 --- a/src/Storages/MergeTree/MergeTreeDataPartBuilder.cpp +++ b/src/Storages/MergeTree/MergeTreeDataPartBuilder.cpp @@ -150,8 +150,7 @@ MergeTreeDataPartBuilder & MergeTreeDataPartBuilder::withPartFormatFromDisk() { if (part_storage) return withPartFormatFromStorage(); - else - return withPartFormatFromVolume(); + return withPartFormatFromVolume(); } MergeTreeDataPartBuilder & MergeTreeDataPartBuilder::withPartFormatFromVolume() diff --git a/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp b/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp index 5c9f872b134..2c487e0ce5a 100644 --- a/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp +++ b/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp @@ -1017,8 +1017,7 @@ size_t MergeTreeDataSelectExecutor::roundRowsOrBytesToMarks( if (bytes_granularity == 0) return res; - else - return std::max(res, (bytes_setting + bytes_granularity - 1) / bytes_granularity); + return std::max(res, (bytes_setting + bytes_granularity - 1) / bytes_granularity); } /// Same as roundRowsOrBytesToMarks() but do not return more then max_marks @@ -1038,16 +1037,13 @@ size_t MergeTreeDataSelectExecutor::minMarksForConcurrentRead( if (bytes_granularity == 0) return marks; - else - { - /// Overflow - if (bytes_setting + bytes_granularity <= bytes_setting) /// overflow - return max_marks; - if (bytes_setting) - return std::max(marks, (bytes_setting + bytes_granularity - 1) / bytes_granularity); - else - return marks; - } + + /// Overflow + if (bytes_setting + bytes_granularity <= bytes_setting) /// overflow + return max_marks; + if (bytes_setting) + return std::max(marks, (bytes_setting + bytes_granularity - 1) / bytes_granularity); + return marks; } @@ -1184,26 +1180,23 @@ MarkRanges MergeTreeDataSelectExecutor::markRangesFromPKRange( /// Empty mark (final mark) return BoolMask(false, true); } - else - { - part_offset_left[0] = part->index_granularity.getMarkStartingRow(range.begin); - part_offset_right[0] = part->index_granularity.getMarkStartingRow(range.end) - 1; - part_offset_left[1] = part->name; - part_offset_right[1] = part->name; - return part_offset_condition->checkInRange( - 2, part_offset_left.data(), part_offset_right.data(), part_offset_types, initial_mask); - } + part_offset_left[0] = part->index_granularity.getMarkStartingRow(range.begin); + part_offset_right[0] = part->index_granularity.getMarkStartingRow(range.end) - 1; + part_offset_left[1] = part->name; + part_offset_right[1] = part->name; + + return part_offset_condition->checkInRange( + 2, part_offset_left.data(), part_offset_right.data(), part_offset_types, initial_mask); }; if (key_condition_useful && part_offset_condition_useful) return check_key_condition() & check_part_offset_condition(); - else if (key_condition_useful) + if (key_condition_useful) return check_key_condition(); - else if (part_offset_condition_useful) + if (part_offset_condition_useful) return check_part_offset_condition(); - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Condition is useless but check_in_range still gets called. It is a bug"); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Condition is useless but check_in_range still gets called. It is a bug"); }; bool key_condition_exact_range = !key_condition_useful || key_condition.matchesExactContinuousRange(); diff --git a/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp b/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp index b796ed7114e..da8d45fdd89 100644 --- a/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexBloomFilter.cpp @@ -185,17 +185,9 @@ bool maybeTrueOnBloomFilter(const IColumn * hash_column, const BloomFilterPtr & hash_functions); }); } - else - { - return std::any_of(hashes.begin(), - hashes.end(), - [&](const auto& hash_row) - { - return hashMatchesFilter(bloom_filter, - hash_row, - hash_functions); - }); - } + + return std::any_of( + hashes.begin(), hashes.end(), [&](const auto & hash_row) { return hashMatchesFilter(bloom_filter, hash_row, hash_functions); }); } } @@ -593,9 +585,8 @@ static bool indexOfCanUseBloomFilter(const RPNBuilderTreeNode * parent) { return true; } - else if (function_name == "equals" /// notEquals is not applicable - || function_name == "greater" || function_name == "greaterOrEquals" - || function_name == "less" || function_name == "lessOrEquals") + if (function_name == "equals" /// notEquals is not applicable + || function_name == "greater" || function_name == "greaterOrEquals" || function_name == "less" || function_name == "lessOrEquals") { size_t function_arguments_size = function.getArgumentsSize(); if (function_arguments_size != 2) @@ -631,17 +622,18 @@ static bool indexOfCanUseBloomFilter(const RPNBuilderTreeNode * parent) /// indexOf(...) = c, c != 0 return true; } - else if (function_name == "notEquals" && constant_equal_zero) + if (function_name == "notEquals" && constant_equal_zero) { /// indexOf(...) != c, c = 0 return true; } - else if (function_name == (reversed ? "less" : "greater") && !applyVisitor(FieldVisitorAccurateLess(), constant_value, zero)) + if (function_name == (reversed ? "less" : "greater") && !applyVisitor(FieldVisitorAccurateLess(), constant_value, zero)) { /// indexOf(...) > c, c >= 0 return true; } - else if (function_name == (reversed ? "lessOrEquals" : "greaterOrEquals") && applyVisitor(FieldVisitorAccurateLess(), zero, constant_value)) + if (function_name == (reversed ? "lessOrEquals" : "greaterOrEquals") + && applyVisitor(FieldVisitorAccurateLess(), zero, constant_value)) { /// indexOf(...) >= c, c > 0 return true; diff --git a/src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp b/src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp index 857b7903588..7c1c425877b 100644 --- a/src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexBloomFilterText.cpp @@ -380,7 +380,7 @@ bool MergeTreeConditionBloomFilterText::extractAtomFromTree(const RPNBuilderTree out.function = RPNElement::FUNCTION_NOT_IN; return true; } - else if (function_name == "in") + if (function_name == "in") { out.function = RPNElement::FUNCTION_IN; return true; @@ -514,7 +514,7 @@ bool MergeTreeConditionBloomFilterText::traverseTreeEquals( return true; } - else if (function_name == "has") + if (function_name == "has") { out.key_column = *key_index; out.function = RPNElement::FUNCTION_HAS; @@ -533,7 +533,7 @@ bool MergeTreeConditionBloomFilterText::traverseTreeEquals( token_extractor->stringToBloomFilter(value.data(), value.size(), *out.bloom_filter); return true; } - else if (function_name == "equals") + if (function_name == "equals") { out.key_column = *key_index; out.function = RPNElement::FUNCTION_EQUALS; @@ -542,7 +542,7 @@ bool MergeTreeConditionBloomFilterText::traverseTreeEquals( token_extractor->stringToBloomFilter(value.data(), value.size(), *out.bloom_filter); return true; } - else if (function_name == "like") + if (function_name == "like") { out.key_column = *key_index; out.function = RPNElement::FUNCTION_EQUALS; @@ -551,7 +551,7 @@ bool MergeTreeConditionBloomFilterText::traverseTreeEquals( token_extractor->stringLikeToBloomFilter(value.data(), value.size(), *out.bloom_filter); return true; } - else if (function_name == "notLike") + if (function_name == "notLike") { out.key_column = *key_index; out.function = RPNElement::FUNCTION_NOT_EQUALS; @@ -560,7 +560,7 @@ bool MergeTreeConditionBloomFilterText::traverseTreeEquals( token_extractor->stringLikeToBloomFilter(value.data(), value.size(), *out.bloom_filter); return true; } - else if (function_name == "startsWith") + if (function_name == "startsWith") { out.key_column = *key_index; out.function = RPNElement::FUNCTION_EQUALS; @@ -569,7 +569,7 @@ bool MergeTreeConditionBloomFilterText::traverseTreeEquals( token_extractor->substringToBloomFilter(value.data(), value.size(), *out.bloom_filter, true, false); return true; } - else if (function_name == "endsWith") + if (function_name == "endsWith") { out.key_column = *key_index; out.function = RPNElement::FUNCTION_EQUALS; @@ -578,13 +578,10 @@ bool MergeTreeConditionBloomFilterText::traverseTreeEquals( token_extractor->substringToBloomFilter(value.data(), value.size(), *out.bloom_filter, false, true); return true; } - else if (function_name == "multiSearchAny" - || function_name == "hasAny") + if (function_name == "multiSearchAny" || function_name == "hasAny") { out.key_column = *key_index; - out.function = function_name == "multiSearchAny" ? - RPNElement::FUNCTION_MULTI_SEARCH : - RPNElement::FUNCTION_HAS_ANY; + out.function = function_name == "multiSearchAny" ? RPNElement::FUNCTION_MULTI_SEARCH : RPNElement::FUNCTION_HAS_ANY; /// 2d vector is not needed here but is used because already exists for FUNCTION_IN std::vector> bloom_filters; @@ -609,7 +606,7 @@ bool MergeTreeConditionBloomFilterText::traverseTreeEquals( out.set_bloom_filters = std::move(bloom_filters); return true; } - else if (function_name == "match") + if (function_name == "match") { out.key_column = *key_index; out.function = RPNElement::FUNCTION_MATCH; @@ -638,7 +635,7 @@ bool MergeTreeConditionBloomFilterText::traverseTreeEquals( out.set_bloom_filters = std::move(bloom_filters); } else - token_extractor->substringToBloomFilter(required_substring.data(), required_substring.size(), *out.bloom_filter, false, false); + token_extractor->substringToBloomFilter(required_substring.data(), required_substring.size(), *out.bloom_filter, false, false); return true; } @@ -753,21 +750,17 @@ MergeTreeIndexPtr bloomFilterIndexTextCreator( return std::make_shared(index, params, std::move(tokenizer)); } - else if (index.type == SplitTokenExtractor::getName()) + if (index.type == SplitTokenExtractor::getName()) { BloomFilterParameters params( - index.arguments[0].safeGet(), - index.arguments[1].safeGet(), - index.arguments[2].safeGet()); + index.arguments[0].safeGet(), index.arguments[1].safeGet(), index.arguments[2].safeGet()); auto tokenizer = std::make_unique(); return std::make_shared(index, params, std::move(tokenizer)); } - else - { - throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown index type: {}", backQuote(index.name)); - } + + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown index type: {}", backQuote(index.name)); } void bloomFilterIndexTextValidator(const IndexDescription & index, bool /*attach*/) diff --git a/src/Storages/MergeTree/MergeTreeIndexFullText.cpp b/src/Storages/MergeTree/MergeTreeIndexFullText.cpp index ba3ca2f139a..f502726763c 100644 --- a/src/Storages/MergeTree/MergeTreeIndexFullText.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexFullText.cpp @@ -418,7 +418,7 @@ bool MergeTreeConditionFullText::traverseAtomAST(const RPNBuilderTreeNode & node out.function = RPNElement::FUNCTION_NOT_IN; return true; } - else if (function_name == "in") + if (function_name == "in") { out.function = RPNElement::FUNCTION_IN; return true; @@ -534,7 +534,7 @@ bool MergeTreeConditionFullText::traverseASTEquals( token_extractor->stringToGinFilter(value.data(), value.size(), *out.gin_filter); return true; } - else if (function_name == "has") + if (function_name == "has") { out.key_column = key_column_num; out.function = RPNElement::FUNCTION_HAS; @@ -553,7 +553,7 @@ bool MergeTreeConditionFullText::traverseASTEquals( token_extractor->stringToGinFilter(value.data(), value.size(), *out.gin_filter); return true; } - else if (function_name == "equals") + if (function_name == "equals") { out.key_column = key_column_num; out.function = RPNElement::FUNCTION_EQUALS; @@ -562,7 +562,7 @@ bool MergeTreeConditionFullText::traverseASTEquals( token_extractor->stringToGinFilter(value.data(), value.size(), *out.gin_filter); return true; } - else if (function_name == "like") + if (function_name == "like") { out.key_column = key_column_num; out.function = RPNElement::FUNCTION_EQUALS; @@ -571,7 +571,7 @@ bool MergeTreeConditionFullText::traverseASTEquals( token_extractor->stringLikeToGinFilter(value.data(), value.size(), *out.gin_filter); return true; } - else if (function_name == "notLike") + if (function_name == "notLike") { out.key_column = key_column_num; out.function = RPNElement::FUNCTION_NOT_EQUALS; @@ -580,7 +580,7 @@ bool MergeTreeConditionFullText::traverseASTEquals( token_extractor->stringLikeToGinFilter(value.data(), value.size(), *out.gin_filter); return true; } - else if (function_name == "hasToken" || function_name == "hasTokenOrNull") + if (function_name == "hasToken" || function_name == "hasTokenOrNull") { out.key_column = key_column_num; out.function = RPNElement::FUNCTION_EQUALS; @@ -589,7 +589,7 @@ bool MergeTreeConditionFullText::traverseASTEquals( token_extractor->stringToGinFilter(value.data(), value.size(), *out.gin_filter); return true; } - else if (function_name == "startsWith") + if (function_name == "startsWith") { out.key_column = key_column_num; out.function = RPNElement::FUNCTION_EQUALS; @@ -598,7 +598,7 @@ bool MergeTreeConditionFullText::traverseASTEquals( token_extractor->substringToGinFilter(value.data(), value.size(), *out.gin_filter, true, false); return true; } - else if (function_name == "endsWith") + if (function_name == "endsWith") { out.key_column = key_column_num; out.function = RPNElement::FUNCTION_EQUALS; @@ -607,7 +607,7 @@ bool MergeTreeConditionFullText::traverseASTEquals( token_extractor->substringToGinFilter(value.data(), value.size(), *out.gin_filter, false, true); return true; } - else if (function_name == "multiSearchAny") + if (function_name == "multiSearchAny") { out.key_column = key_column_num; out.function = RPNElement::FUNCTION_MULTI_SEARCH; @@ -627,7 +627,7 @@ bool MergeTreeConditionFullText::traverseASTEquals( out.set_gin_filters = std::move(gin_filters); return true; } - else if (function_name == "match") + if (function_name == "match") { out.key_column = key_column_num; out.function = RPNElement::FUNCTION_MATCH; @@ -649,8 +649,8 @@ bool MergeTreeConditionFullText::traverseASTEquals( gin_filters.emplace_back(); for (const auto & alternative : alternatives) { - gin_filters.back().emplace_back(params); - token_extractor->substringToGinFilter(alternative.data(), alternative.size(), gin_filters.back().back(), false, false); + gin_filters.back().emplace_back(params); + token_extractor->substringToGinFilter(alternative.data(), alternative.size(), gin_filters.back().back(), false, false); } out.set_gin_filters = std::move(gin_filters); } @@ -661,7 +661,6 @@ bool MergeTreeConditionFullText::traverseASTEquals( } return true; - } return false; @@ -786,11 +785,9 @@ MergeTreeIndexPtr fullTextIndexCreator( auto tokenizer = std::make_unique(n); return std::make_shared(index, params, std::move(tokenizer)); } - else - { - auto tokenizer = std::make_unique(); - return std::make_shared(index, params, std::move(tokenizer)); - } + + auto tokenizer = std::make_unique(); + return std::make_shared(index, params, std::move(tokenizer)); } void fullTextIndexValidator(const IndexDescription & index, bool /*attach*/) diff --git a/src/Storages/MergeTree/MergeTreeIndexGranularity.cpp b/src/Storages/MergeTree/MergeTreeIndexGranularity.cpp index 16902540738..467d2567df1 100644 --- a/src/Storages/MergeTree/MergeTreeIndexGranularity.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexGranularity.cpp @@ -22,8 +22,7 @@ size_t MergeTreeIndexGranularity::getMarkRows(size_t mark_index) const throw Exception(ErrorCodes::LOGICAL_ERROR, "Trying to get non existing mark {}, while size is {}", mark_index, getMarksCount()); if (mark_index == 0) return marks_rows_partial_sums[0]; - else - return marks_rows_partial_sums[mark_index] - marks_rows_partial_sums[mark_index - 1]; + return marks_rows_partial_sums[mark_index] - marks_rows_partial_sums[mark_index - 1]; } size_t MergeTreeIndexGranularity::getMarkStartingRow(size_t mark_index) const diff --git a/src/Storages/MergeTree/MergeTreeIndexGranularityInfo.cpp b/src/Storages/MergeTree/MergeTreeIndexGranularityInfo.cpp index f79aa0b146d..6aaa5aee14c 100644 --- a/src/Storages/MergeTree/MergeTreeIndexGranularityInfo.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexGranularityInfo.cpp @@ -133,10 +133,9 @@ size_t MergeTreeIndexGranularityInfo::getMarkSizeInBytes(size_t columns_num) con { if (mark_type.part_type == MergeTreeDataPartType::Wide) return mark_type.adaptive ? getAdaptiveMrkSizeWide() : getNonAdaptiveMrkSizeWide(); - else if (mark_type.part_type == MergeTreeDataPartType::Compact) + if (mark_type.part_type == MergeTreeDataPartType::Compact) return getAdaptiveMrkSizeCompact(columns_num); - else - throw Exception(ErrorCodes::UNKNOWN_PART_TYPE, "Unknown part type"); + throw Exception(ErrorCodes::UNKNOWN_PART_TYPE, "Unknown part type"); } std::string MergeTreeIndexGranularityInfo::describe() const diff --git a/src/Storages/MergeTree/MergeTreeIndexMinMax.cpp b/src/Storages/MergeTree/MergeTreeIndexMinMax.cpp index c60d63a59ba..db0481f4434 100644 --- a/src/Storages/MergeTree/MergeTreeIndexMinMax.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexMinMax.cpp @@ -207,7 +207,7 @@ MergeTreeIndexFormat MergeTreeIndexMinMax::getDeserializedFormat(const IDataPart { if (data_part_storage.exists(relative_path_prefix + ".idx2")) return {2, ".idx2"}; - else if (data_part_storage.exists(relative_path_prefix + ".idx")) + if (data_part_storage.exists(relative_path_prefix + ".idx")) return {1, ".idx"}; return {0 /* unknown */, ""}; } diff --git a/src/Storages/MergeTree/MergeTreeIndexSet.cpp b/src/Storages/MergeTree/MergeTreeIndexSet.cpp index 497520a94f2..142a09cc086 100644 --- a/src/Storages/MergeTree/MergeTreeIndexSet.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexSet.cpp @@ -485,7 +485,7 @@ const ActionsDAG::Node * MergeTreeIndexConditionSet::operatorFromDAG(const Actio auto bit_swap_last_two_function = FunctionFactory::instance().get("__bitSwapLastTwo", context); return &result_dag.addFunction(bit_swap_last_two_function, {argument}, {}); } - else if (function_name == "and" || function_name == "indexHint" || function_name == "or") + if (function_name == "and" || function_name == "indexHint" || function_name == "or") { if (arguments_size < 1) return nullptr; @@ -535,13 +535,13 @@ bool MergeTreeIndexConditionSet::checkDAGUseless(const ActionsDAG::Node & node, sets_to_prepare.push_back(set); return false; } - else if (node.column && isColumnConst(*node.column)) + if (node.column && isColumnConst(*node.column)) { Field literal; node.column->get(0, literal); return !atomic && literal.safeGet(); } - else if (node.type == ActionsDAG::ActionType::FUNCTION) + if (node.type == ActionsDAG::ActionType::FUNCTION) { auto column_name = tree_node.getColumnName(); if (key_columns.contains(column_name)) @@ -562,13 +562,17 @@ bool MergeTreeIndexConditionSet::checkDAGUseless(const ActionsDAG::Node & node, } return all_useless; } - else if (function_name == "or") - return std::any_of(arguments.begin(), arguments.end(), [&, atomic](const auto & arg) { return checkDAGUseless(*arg, context, sets_to_prepare, atomic); }); - else if (function_name == "not") + if (function_name == "or") + return std::any_of( + arguments.begin(), + arguments.end(), + [&, atomic](const auto & arg) { return checkDAGUseless(*arg, context, sets_to_prepare, atomic); }); + if (function_name == "not") return checkDAGUseless(*arguments.at(0), context, sets_to_prepare, atomic); - else - return std::any_of(arguments.begin(), arguments.end(), - [&](const auto & arg) { return checkDAGUseless(*arg, context, sets_to_prepare, true /*atomic*/); }); + return std::any_of( + arguments.begin(), + arguments.end(), + [&](const auto & arg) { return checkDAGUseless(*arg, context, sets_to_prepare, true /*atomic*/); }); } auto column_name = tree_node.getColumnName(); @@ -602,7 +606,7 @@ void setIndexValidator(const IndexDescription & index, bool /*attach*/) { if (index.arguments.size() != 1) throw Exception(ErrorCodes::INCORRECT_QUERY, "Set index must have exactly one argument."); - else if (index.arguments[0].getType() != Field::Types::UInt64) + if (index.arguments[0].getType() != Field::Types::UInt64) throw Exception(ErrorCodes::INCORRECT_QUERY, "Set index argument must be positive integer."); } diff --git a/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp b/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp index 8d9eebd1d70..9bea7f650c1 100644 --- a/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp +++ b/src/Storages/MergeTree/MergeTreeIndexVectorSimilarity.cpp @@ -102,10 +102,10 @@ USearchIndexWithSerialization::USearchIndexWithSerialization( unum::usearch::index_dense_config_t config(usearch_hnsw_params.m, usearch_hnsw_params.ef_construction, usearch_hnsw_params.ef_search); config.enable_key_lookups = false; /// we don't do row-to-vector lookups - if (auto result = USearchIndex::make(metric, config); !result) + auto result = USearchIndex::make(metric, config); + if (!result) throw Exception(ErrorCodes::INCORRECT_DATA, "Could not create vector similarity index. Error: {}", String(result.error.release())); - else - swap(result.index); + swap(result.index); } void USearchIndexWithSerialization::serialize(WriteBuffer & ostr) const @@ -291,16 +291,15 @@ void updateImpl(const ColumnArray * column_array, const ColumnArray::Offsets & c CurrentThread::attachToGroupIfDetached(thread_group); /// add is thread-safe - if (auto result = index->add(key, &column_array_data_float_data[column_array_offsets[row - 1]]); !result) + auto result = index->add(key, &column_array_data_float_data[column_array_offsets[row - 1]]); + if (!result) { throw Exception(ErrorCodes::INCORRECT_DATA, "Could not add data to vector similarity index. Error: {}", String(result.error.release())); } - else - { - ProfileEvents::increment(ProfileEvents::USearchAddCount); - ProfileEvents::increment(ProfileEvents::USearchAddVisitedMembers, result.visited_members); - ProfileEvents::increment(ProfileEvents::USearchAddComputedDistances, result.computed_distances); - } + + ProfileEvents::increment(ProfileEvents::USearchAddCount); + ProfileEvents::increment(ProfileEvents::USearchAddVisitedMembers, result.visited_members); + ProfileEvents::increment(ProfileEvents::USearchAddComputedDistances, result.computed_distances); }; size_t index_size = index->size(); diff --git a/src/Storages/MergeTree/MergeTreeIndices.cpp b/src/Storages/MergeTree/MergeTreeIndices.cpp index d2fc0e84b56..dd38f5e69b6 100644 --- a/src/Storages/MergeTree/MergeTreeIndices.cpp +++ b/src/Storages/MergeTree/MergeTreeIndices.cpp @@ -43,8 +43,7 @@ MergeTreeIndexPtr MergeTreeIndexFactory::get( { if (left.empty()) return right.first; - else - return left + ", " + right.first; + return left + ", " + right.first; }) ); } @@ -98,8 +97,7 @@ void MergeTreeIndexFactory::validate(const IndexDescription & index, bool attach { if (left.empty()) return right.first; - else - return left + ", " + right.first; + return left + ", " + right.first; }) ); } diff --git a/src/Storages/MergeTree/MergeTreeMutationStatus.cpp b/src/Storages/MergeTree/MergeTreeMutationStatus.cpp index 54098a65cd0..6553054774e 100644 --- a/src/Storages/MergeTree/MergeTreeMutationStatus.cpp +++ b/src/Storages/MergeTree/MergeTreeMutationStatus.cpp @@ -21,7 +21,7 @@ void checkMutationStatus(std::optional & status, const { throw Exception(ErrorCodes::UNFINISHED, "Mutation {} was killed", *mutation_ids.begin()); } - else if (!status->is_done && !status->latest_fail_reason.empty()) + if (!status->is_done && !status->latest_fail_reason.empty()) { throw Exception( ErrorCodes::UNFINISHED, diff --git a/src/Storages/MergeTree/MergeTreePartInfo.cpp b/src/Storages/MergeTree/MergeTreePartInfo.cpp index f3a974a22af..c1871654d27 100644 --- a/src/Storages/MergeTree/MergeTreePartInfo.cpp +++ b/src/Storages/MergeTree/MergeTreePartInfo.cpp @@ -20,8 +20,7 @@ MergeTreePartInfo MergeTreePartInfo::fromPartName(const String & part_name, Merg { if (auto part_opt = tryParsePartName(part_name, format_version)) return *part_opt; - else - throw Exception(ErrorCodes::BAD_DATA_PART_NAME, "Unexpected part name: {} for format version: {}", part_name, format_version); + throw Exception(ErrorCodes::BAD_DATA_PART_NAME, "Unexpected part name: {} for format version: {}", part_name, format_version); } void MergeTreePartInfo::validatePartitionID(const ASTPtr & partition_id_ast, MergeTreeDataFormatVersion format_version) diff --git a/src/Storages/MergeTree/MergeTreePartsMover.cpp b/src/Storages/MergeTree/MergeTreePartsMover.cpp index 221da9f97a0..a826cd3b794 100644 --- a/src/Storages/MergeTree/MergeTreePartsMover.cpp +++ b/src/Storages/MergeTree/MergeTreePartsMover.cpp @@ -216,8 +216,7 @@ bool MergeTreePartsMover::selectPartsForMove( LOG_DEBUG(log, "Selected {} parts to move according to storage policy rules and {} parts according to TTL rules, {} total", parts_to_move_by_policy_rules, parts_to_move_by_ttl_rules, ReadableSize(parts_to_move_total_size_bytes)); return true; } - else - return false; + return false; } MergeTreePartsMover::TemporaryClonedPart MergeTreePartsMover::clonePart(const MergeTreeMoveEntry & moving_part, const ReadSettings & read_settings, const WriteSettings & write_settings) const diff --git a/src/Storages/MergeTree/MergeTreeRangeReader.cpp b/src/Storages/MergeTree/MergeTreeRangeReader.cpp index e88ded5437d..32d6c41bdcb 100644 --- a/src/Storages/MergeTree/MergeTreeRangeReader.cpp +++ b/src/Storages/MergeTree/MergeTreeRangeReader.cpp @@ -141,17 +141,15 @@ size_t MergeTreeRangeReader::DelayedStream::read(Columns & columns, size_t from_ num_delayed_rows += num_rows; return 0; } - else - { - size_t read_rows = finalize(columns); - continue_reading = false; - current_mark = from_mark; - current_offset = offset; - num_delayed_rows = num_rows; + size_t read_rows = finalize(columns); - return read_rows; - } + continue_reading = false; + current_mark = from_mark; + current_offset = offset; + num_delayed_rows = num_rows; + + return read_rows; } size_t MergeTreeRangeReader::DelayedStream::finalize(Columns & columns) @@ -266,18 +264,16 @@ size_t MergeTreeRangeReader::Stream::read(Columns & columns, size_t num_rows, bo return read_rows; } - else - { - /// Nothing to read. - if (skip_remaining_rows_in_current_granule) - { - /// Skip the rest of the rows in granule and start new one. - checkNotFinished(); - toNextMark(); - } - return 0; + /// Nothing to read. + if (skip_remaining_rows_in_current_granule) + { + /// Skip the rest of the rows in granule and start new one. + checkNotFinished(); + toNextMark(); } + + return 0; } void MergeTreeRangeReader::Stream::skip(size_t num_rows) @@ -539,14 +535,14 @@ void MergeTreeRangeReader::ReadResult::optimize(const FilterWithCachedCount & cu clear(); return; } - else if (total_zero_rows_in_tails == 0 && filter.countBytesInFilter() == filter.size()) + if (total_zero_rows_in_tails == 0 && filter.countBytesInFilter() == filter.size()) { LOG_TEST(log, "ReadResult::optimize() combined filter is const True"); setFilterConstTrue(); return; } /// Just a guess. If only a few rows may be skipped, it's better not to skip at all. - else if (2 * total_zero_rows_in_tails > filter.size()) + if (2 * total_zero_rows_in_tails > filter.size()) { const NumRows rows_per_granule_previous = rows_per_granule; const size_t total_rows_per_granule_previous = total_rows_per_granule; @@ -561,8 +557,8 @@ void MergeTreeRangeReader::ReadResult::optimize(const FilterWithCachedCount & cu /// Check if const 1 after shrink. /// We can apply shrink only if after the previous step the number of rows in the result /// matches the rows_per_granule info. Otherwise we will not be able to match newly added zeros in granule tails. - if (num_rows == total_rows_per_granule_previous && - filter.countBytesInFilter() + total_zero_rows_in_tails == total_rows_per_granule_previous) /// All zeros are in tails? + if (num_rows == total_rows_per_granule_previous + && filter.countBytesInFilter() + total_zero_rows_in_tails == total_rows_per_granule_previous) /// All zeros are in tails? { setFilterConstTrue(); @@ -584,8 +580,11 @@ void MergeTreeRangeReader::ReadResult::optimize(const FilterWithCachedCount & cu /// Shorten the filter by removing zeros from granule tails collapseZeroTails(filter.getData(), rows_per_granule_previous, new_data); if (total_rows_per_granule != new_filter->size()) - throw Exception(ErrorCodes::LOGICAL_ERROR, "New filter size {} doesn't match number of rows to be read {}", - new_filter->size(), total_rows_per_granule); + throw Exception( + ErrorCodes::LOGICAL_ERROR, + "New filter size {} doesn't match number of rows to be read {}", + new_filter->size(), + total_rows_per_granule); /// Need to apply combined filter here before replacing it with shortened one because otherwise /// the filter size will not match the number of rows in the result columns. @@ -602,8 +601,11 @@ void MergeTreeRangeReader::ReadResult::optimize(const FilterWithCachedCount & cu final_filter = FilterWithCachedCount(new_filter->getPtr()); if (num_rows != final_filter.countBytesInFilter()) - throw Exception(ErrorCodes::LOGICAL_ERROR, "Count of 1s in final filter {} doesn't match number of rows {}", - final_filter.countBytesInFilter(), num_rows); + throw Exception( + ErrorCodes::LOGICAL_ERROR, + "Count of 1s in final filter {} doesn't match number of rows {}", + final_filter.countBytesInFilter(), + num_rows); LOG_TEST(log, "ReadResult::optimize() after colapseZeroTails {}", dumpInfo()); } @@ -737,7 +739,7 @@ size_t MergeTreeRangeReader::ReadResult::numZerosInTail(const UInt8 * begin, con /// check if cpu support avx512 dynamically, haveAVX512BW contains check of haveAVX512F if (isArchSupported(TargetArch::AVX512BW)) return TargetSpecific::AVX512BW::numZerosInTail(begin, end); - else if (isArchSupported(TargetArch::AVX2)) + if (isArchSupported(TargetArch::AVX2)) return TargetSpecific::AVX2::numZerosInTail(begin, end); #endif diff --git a/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp b/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp index a7ed91c8fc1..76bcf41d6d8 100644 --- a/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp +++ b/src/Storages/MergeTree/MergeTreeSelectProcessor.cpp @@ -213,10 +213,8 @@ ChunkAndProgress MergeTreeSelectProcessor::read() .num_read_bytes = res.num_read_bytes, .is_finished = false}; } - else - { - return {Chunk(), res.num_read_rows, res.num_read_bytes, false}; - } + + return {Chunk(), res.num_read_rows, res.num_read_bytes, false}; } return {Chunk(), 0, 0, true}; diff --git a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp index a2bf45e21aa..cc33628e84d 100644 --- a/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp +++ b/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp @@ -236,12 +236,12 @@ static bool isConditionGood(const RPNBuilderTreeNode & condition, const NameSet const auto value = output_value.safeGet(); return value > threshold; } - else if (type == Field::Types::Int64) + if (type == Field::Types::Int64) { const auto value = output_value.safeGet(); return value < -threshold || threshold < value; } - else if (type == Field::Types::Float64) + if (type == Field::Types::Float64) { const auto value = output_value.safeGet(); return value < -threshold || threshold < value; diff --git a/src/Storages/MergeTree/MutateFromLogEntryTask.cpp b/src/Storages/MergeTree/MutateFromLogEntryTask.cpp index c78e37cbe74..54215cd2dba 100644 --- a/src/Storages/MergeTree/MutateFromLogEntryTask.cpp +++ b/src/Storages/MergeTree/MutateFromLogEntryTask.cpp @@ -188,7 +188,7 @@ ReplicatedMergeMutateTaskBase::PrepareResult MutateFromLogEntryTask::prepare() .part_log_writer = part_log_writer, }; } - else if (storage.findReplicaHavingCoveringPart(entry.new_part_name, /* active */ false)) + if (storage.findReplicaHavingCoveringPart(entry.new_part_name, /* active */ false)) { /// Why this if still needed? We can check for part in zookeeper, don't find it and sleep for any amount of time. During this sleep part will be actually committed from other replica /// and exclusive zero copy lock will be released. We will take the lock and execute mutation one more time, while it was possible just to download the part from other replica. @@ -200,17 +200,19 @@ ReplicatedMergeMutateTaskBase::PrepareResult MutateFromLogEntryTask::prepare() /// In case of DROP_RANGE on fast replica and stale replica we can have some failed select queries in case of zero copy replication. zero_copy_lock->lock->unlock(); - LOG_DEBUG(log, "We took zero copy lock, but mutation of part {} finished by some other replica, will release lock and download mutated part to avoid data duplication", entry.new_part_name); + LOG_DEBUG( + log, + "We took zero copy lock, but mutation of part {} finished by some other replica, will release lock and download " + "mutated part to avoid data duplication", + entry.new_part_name); return PrepareResult{ .prepared_successfully = false, .need_to_check_missing_part_in_fetch = true, .part_log_writer = part_log_writer, }; } - else - { - LOG_DEBUG(log, "Zero copy lock taken, will mutate part {}", entry.new_part_name); - } + + LOG_DEBUG(log, "Zero copy lock taken, will mutate part {}", entry.new_part_name); } } diff --git a/src/Storages/MergeTree/MutateTask.cpp b/src/Storages/MergeTree/MutateTask.cpp index c16c445f6ae..2e7847fc99f 100644 --- a/src/Storages/MergeTree/MutateTask.cpp +++ b/src/Storages/MergeTree/MutateTask.cpp @@ -2214,10 +2214,9 @@ bool MutateTask::prepare() promise.set_value(std::move(part)); return false; } - else - { - LOG_TRACE(ctx->log, "Mutating part {} to mutation version {}", ctx->source_part->name, ctx->future_part->part_info.mutation); - } + + LOG_TRACE(ctx->log, "Mutating part {} to mutation version {}", ctx->source_part->name, ctx->future_part->part_info.mutation); + /// We must read with one thread because it guarantees that output stream will be sorted. /// Disable all settings that can enable reading with several streams. diff --git a/src/Storages/MergeTree/ParallelReplicasReadingCoordinator.cpp b/src/Storages/MergeTree/ParallelReplicasReadingCoordinator.cpp index 62115015817..4d5ad806177 100644 --- a/src/Storages/MergeTree/ParallelReplicasReadingCoordinator.cpp +++ b/src/Storages/MergeTree/ParallelReplicasReadingCoordinator.cpp @@ -609,13 +609,13 @@ void DefaultCoordinator::tryToStealFromQueue( } if (can_take) { - if (auto taken = takeFromRange(range, min_number_of_marks, current_marks_amount, result); taken == range.getNumberOfMarks()) + auto taken = takeFromRange(range, min_number_of_marks, current_marks_amount, result); + if (taken == range.getNumberOfMarks()) { it = decltype(it)(queue.erase(std::next(it).base())); continue; } - else - range.begin += taken; + range.begin += taken; } } diff --git a/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.cpp b/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.cpp index 7a46132ef1a..935160d3660 100644 --- a/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.cpp +++ b/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.cpp @@ -196,8 +196,7 @@ PartMovesBetweenShardsOrchestrator::Entry PartMovesBetweenShardsOrchestrator::st return entry; } /// The forward transition happens implicitly when task is created by `StorageReplicatedMergeTree::movePartitionToShard`. - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected entry state ({}) in stepEntry. This is a bug.", entry.state.toString()); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unexpected entry state ({}) in stepEntry. This is a bug.", entry.state.toString()); } case EntryState::SYNC_SOURCE: @@ -207,53 +206,52 @@ PartMovesBetweenShardsOrchestrator::Entry PartMovesBetweenShardsOrchestrator::st entry.state = EntryState::TODO; return entry; } + + ReplicatedMergeTreeLogEntryData sync_source_log_entry; + + String sync_source_log_entry_barrier_path = fs::path(entry.znode_path) / ("log_" + entry.state.toString()); + Coordination::Stat sync_source_log_entry_stat; + String sync_source_log_entry_str; + if (zk->tryGet(sync_source_log_entry_barrier_path, sync_source_log_entry_str, &sync_source_log_entry_stat)) + { + LOG_DEBUG(log, "Log entry was already created will check the existing one."); + + sync_source_log_entry + = *ReplicatedMergeTreeLogEntry::parse(sync_source_log_entry_str, sync_source_log_entry_stat, storage.format_version); + } else { - ReplicatedMergeTreeLogEntryData sync_source_log_entry; + /// Log entry. + Coordination::Requests ops; + ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); - String sync_source_log_entry_barrier_path = fs::path(entry.znode_path) / ("log_" + entry.state.toString()); - Coordination::Stat sync_source_log_entry_stat; - String sync_source_log_entry_str; - if (zk->tryGet(sync_source_log_entry_barrier_path, sync_source_log_entry_str, &sync_source_log_entry_stat)) - { - LOG_DEBUG(log, "Log entry was already created will check the existing one."); + sync_source_log_entry.type = ReplicatedMergeTreeLogEntryData::SYNC_PINNED_PART_UUIDS; + sync_source_log_entry.log_entry_id = sync_source_log_entry_barrier_path; + sync_source_log_entry.create_time = std::time(nullptr); + sync_source_log_entry.source_replica = storage.replica_name; - sync_source_log_entry = *ReplicatedMergeTreeLogEntry::parse(sync_source_log_entry_str, sync_source_log_entry_stat, - storage.format_version); - } - else - { - /// Log entry. - Coordination::Requests ops; - ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); + ops.emplace_back(zkutil::makeCreateRequest(sync_source_log_entry_barrier_path, sync_source_log_entry.toString(), -1)); + ops.emplace_back(zkutil::makeSetRequest(zookeeper_path + "/log", "", -1)); + ops.emplace_back(zkutil::makeCreateRequest( + zookeeper_path + "/log/log-", sync_source_log_entry.toString(), zkutil::CreateMode::PersistentSequential)); - sync_source_log_entry.type = ReplicatedMergeTreeLogEntryData::SYNC_PINNED_PART_UUIDS; - sync_source_log_entry.log_entry_id = sync_source_log_entry_barrier_path; - sync_source_log_entry.create_time = std::time(nullptr); - sync_source_log_entry.source_replica = storage.replica_name; + Coordination::Responses responses; + Coordination::Error rc = zk->tryMulti(ops, responses); + zkutil::KeeperMultiException::check(rc, ops, responses); - ops.emplace_back(zkutil::makeCreateRequest(sync_source_log_entry_barrier_path, sync_source_log_entry.toString(), -1)); - ops.emplace_back(zkutil::makeSetRequest(zookeeper_path + "/log", "", -1)); - ops.emplace_back(zkutil::makeCreateRequest( - zookeeper_path + "/log/log-", sync_source_log_entry.toString(), zkutil::CreateMode::PersistentSequential)); + String log_znode_path = dynamic_cast(*responses.back()).path_created; + sync_source_log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); - Coordination::Responses responses; - Coordination::Error rc = zk->tryMulti(ops, responses); - zkutil::KeeperMultiException::check(rc, ops, responses); - - String log_znode_path = dynamic_cast(*responses.back()).path_created; - sync_source_log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); - - LOG_DEBUG(log, "Pushed log entry: {}", log_znode_path); - } - - Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(zookeeper_path, sync_source_log_entry, 1); - if (!unwaited.empty()) - throw Exception(ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); - - entry.state = EntryState::SYNC_DESTINATION; - return entry; + LOG_DEBUG(log, "Pushed log entry: {}", log_znode_path); } + + Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(zookeeper_path, sync_source_log_entry, 1); + if (!unwaited.empty()) + throw Exception( + ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); + + entry.state = EntryState::SYNC_DESTINATION; + return entry; } case EntryState::SYNC_DESTINATION: @@ -264,55 +262,54 @@ PartMovesBetweenShardsOrchestrator::Entry PartMovesBetweenShardsOrchestrator::st entry_copy.state = EntryState::SYNC_SOURCE; return entry_copy; } + + ReplicatedMergeTreeLogEntryData sync_destination_log_entry; + + String sync_destination_log_entry_barrier_path = fs::path(entry.znode_path) / ("log_" + entry.state.toString()); + Coordination::Stat sync_destination_log_entry_stat; + String sync_destination_log_entry_str; + if (zk->tryGet(sync_destination_log_entry_barrier_path, sync_destination_log_entry_str, &sync_destination_log_entry_stat)) + { + LOG_DEBUG(log, "Log entry was already created will check the existing one."); + + sync_destination_log_entry = *ReplicatedMergeTreeLogEntry::parse( + sync_destination_log_entry_str, sync_destination_log_entry_stat, storage.format_version); + } else { - ReplicatedMergeTreeLogEntryData sync_destination_log_entry; + /// Log entry. + Coordination::Requests ops; + ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); - String sync_destination_log_entry_barrier_path = fs::path(entry.znode_path) / ("log_" + entry.state.toString()); - Coordination::Stat sync_destination_log_entry_stat; - String sync_destination_log_entry_str; - if (zk->tryGet(sync_destination_log_entry_barrier_path, sync_destination_log_entry_str, &sync_destination_log_entry_stat)) - { - LOG_DEBUG(log, "Log entry was already created will check the existing one."); + sync_destination_log_entry.type = ReplicatedMergeTreeLogEntryData::SYNC_PINNED_PART_UUIDS; + sync_destination_log_entry.log_entry_id = sync_destination_log_entry_barrier_path; + sync_destination_log_entry.create_time = std::time(nullptr); + sync_destination_log_entry.source_replica = storage.replica_name; + sync_destination_log_entry.source_shard = zookeeper_path; - sync_destination_log_entry = *ReplicatedMergeTreeLogEntry::parse(sync_destination_log_entry_str, - sync_destination_log_entry_stat, - storage.format_version); - } - else - { - /// Log entry. - Coordination::Requests ops; - ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); + ops.emplace_back( + zkutil::makeCreateRequest(sync_destination_log_entry_barrier_path, sync_destination_log_entry.toString(), -1)); + ops.emplace_back(zkutil::makeSetRequest(entry.to_shard + "/log", "", -1)); + ops.emplace_back(zkutil::makeCreateRequest( + entry.to_shard + "/log/log-", sync_destination_log_entry.toString(), zkutil::CreateMode::PersistentSequential)); - sync_destination_log_entry.type = ReplicatedMergeTreeLogEntryData::SYNC_PINNED_PART_UUIDS; - sync_destination_log_entry.log_entry_id = sync_destination_log_entry_barrier_path; - sync_destination_log_entry.create_time = std::time(nullptr); - sync_destination_log_entry.source_replica = storage.replica_name; - sync_destination_log_entry.source_shard = zookeeper_path; + Coordination::Responses responses; + Coordination::Error rc = zk->tryMulti(ops, responses); + zkutil::KeeperMultiException::check(rc, ops, responses); - ops.emplace_back(zkutil::makeCreateRequest(sync_destination_log_entry_barrier_path, sync_destination_log_entry.toString(), -1)); - ops.emplace_back(zkutil::makeSetRequest(entry.to_shard + "/log", "", -1)); - ops.emplace_back(zkutil::makeCreateRequest( - entry.to_shard + "/log/log-", sync_destination_log_entry.toString(), zkutil::CreateMode::PersistentSequential)); + String log_znode_path = dynamic_cast(*responses.back()).path_created; + sync_destination_log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); - Coordination::Responses responses; - Coordination::Error rc = zk->tryMulti(ops, responses); - zkutil::KeeperMultiException::check(rc, ops, responses); - - String log_znode_path = dynamic_cast(*responses.back()).path_created; - sync_destination_log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); - - LOG_DEBUG(log, "Pushed log entry: {}", log_znode_path); - } - - Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(entry.to_shard, sync_destination_log_entry, 1); - if (!unwaited.empty()) - throw Exception(ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); - - entry.state = EntryState::DESTINATION_FETCH; - return entry; + LOG_DEBUG(log, "Pushed log entry: {}", log_znode_path); } + + Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(entry.to_shard, sync_destination_log_entry, 1); + if (!unwaited.empty()) + throw Exception( + ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); + + entry.state = EntryState::DESTINATION_FETCH; + return entry; } case EntryState::DESTINATION_FETCH: @@ -327,55 +324,53 @@ PartMovesBetweenShardsOrchestrator::Entry PartMovesBetweenShardsOrchestrator::st entry.state = EntryState::SYNC_DESTINATION; return entry; } + + /// Note: Table structure shouldn't be changed while there are part movements in progress. + + ReplicatedMergeTreeLogEntryData fetch_log_entry; + + String fetch_log_entry_barrier_path = fs::path(entry.znode_path) / ("log_" + entry.state.toString()); + Coordination::Stat fetch_log_entry_stat; + String fetch_log_entry_str; + if (zk->tryGet(fetch_log_entry_barrier_path, fetch_log_entry_str, &fetch_log_entry_stat)) + { + LOG_DEBUG(log, "Log entry was already created will check the existing one."); + + fetch_log_entry = *ReplicatedMergeTreeLogEntry::parse(fetch_log_entry_str, fetch_log_entry_stat, storage.format_version); + } else { - /// Note: Table structure shouldn't be changed while there are part movements in progress. + Coordination::Requests ops; + ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); - ReplicatedMergeTreeLogEntryData fetch_log_entry; + fetch_log_entry.type = ReplicatedMergeTreeLogEntryData::CLONE_PART_FROM_SHARD; + fetch_log_entry.log_entry_id = fetch_log_entry_barrier_path; + fetch_log_entry.create_time = std::time(nullptr); + fetch_log_entry.new_part_name = entry.part_name; + fetch_log_entry.source_replica = storage.replica_name; + fetch_log_entry.source_shard = zookeeper_path; + ops.emplace_back(zkutil::makeCreateRequest(fetch_log_entry_barrier_path, fetch_log_entry.toString(), -1)); + ops.emplace_back(zkutil::makeSetRequest(entry.to_shard + "/log", "", -1)); + ops.emplace_back(zkutil::makeCreateRequest( + entry.to_shard + "/log/log-", fetch_log_entry.toString(), zkutil::CreateMode::PersistentSequential)); - String fetch_log_entry_barrier_path = fs::path(entry.znode_path) / ("log_" + entry.state.toString()); - Coordination::Stat fetch_log_entry_stat; - String fetch_log_entry_str; - if (zk->tryGet(fetch_log_entry_barrier_path, fetch_log_entry_str, &fetch_log_entry_stat)) - { - LOG_DEBUG(log, "Log entry was already created will check the existing one."); + Coordination::Responses responses; + Coordination::Error rc = zk->tryMulti(ops, responses); + zkutil::KeeperMultiException::check(rc, ops, responses); - fetch_log_entry = *ReplicatedMergeTreeLogEntry::parse(fetch_log_entry_str, fetch_log_entry_stat, - storage.format_version); - } - else - { - Coordination::Requests ops; - ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); + String log_znode_path = dynamic_cast(*responses.back()).path_created; + fetch_log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); - fetch_log_entry.type = ReplicatedMergeTreeLogEntryData::CLONE_PART_FROM_SHARD; - fetch_log_entry.log_entry_id = fetch_log_entry_barrier_path; - fetch_log_entry.create_time = std::time(nullptr); - fetch_log_entry.new_part_name = entry.part_name; - fetch_log_entry.source_replica = storage.replica_name; - fetch_log_entry.source_shard = zookeeper_path; - ops.emplace_back(zkutil::makeCreateRequest(fetch_log_entry_barrier_path, fetch_log_entry.toString(), -1)); - ops.emplace_back(zkutil::makeSetRequest(entry.to_shard + "/log", "", -1)); - ops.emplace_back(zkutil::makeCreateRequest( - entry.to_shard + "/log/log-", fetch_log_entry.toString(), zkutil::CreateMode::PersistentSequential)); - - Coordination::Responses responses; - Coordination::Error rc = zk->tryMulti(ops, responses); - zkutil::KeeperMultiException::check(rc, ops, responses); - - String log_znode_path = dynamic_cast(*responses.back()).path_created; - fetch_log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); - - LOG_DEBUG(log, "Pushed log entry: {}", log_znode_path); - } - - Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(entry.to_shard, fetch_log_entry, 1); - if (!unwaited.empty()) - throw Exception(ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); - - entry.state = EntryState::DESTINATION_ATTACH; - return entry; + LOG_DEBUG(log, "Pushed log entry: {}", log_znode_path); } + + Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(entry.to_shard, fetch_log_entry, 1); + if (!unwaited.empty()) + throw Exception( + ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); + + entry.state = EntryState::DESTINATION_ATTACH; + return entry; } case EntryState::DESTINATION_ATTACH: @@ -394,133 +389,133 @@ PartMovesBetweenShardsOrchestrator::Entry PartMovesBetweenShardsOrchestrator::st entry.state = EntryState::DESTINATION_FETCH; return entry; } + + // Need to remove ATTACH_PART from the queue or drop data. + // Similar to `StorageReplicatedMergeTree::dropPart` without extra + // checks as we know drop shall be possible. + ReplicatedMergeTreeLogEntryData attach_rollback_log_entry; + + String attach_rollback_log_entry_barrier_path + = fs::path(entry.znode_path) / ("log_" + entry.state.toString() + "_rollback"); + Coordination::Stat attach_rollback_log_entry_stat; + String attach_rollback_log_entry_str; + if (zk->tryGet(attach_rollback_log_entry_barrier_path, attach_rollback_log_entry_str, &attach_rollback_log_entry_stat)) + { + LOG_DEBUG(log, "Log entry was already created will check the existing one."); + + attach_rollback_log_entry = *ReplicatedMergeTreeLogEntry::parse( + attach_rollback_log_entry_str, attach_rollback_log_entry_stat, storage.format_version); + } else { - // Need to remove ATTACH_PART from the queue or drop data. - // Similar to `StorageReplicatedMergeTree::dropPart` without extra - // checks as we know drop shall be possible. - ReplicatedMergeTreeLogEntryData attach_rollback_log_entry; + const auto attach_log_entry + = ReplicatedMergeTreeLogEntry::parse(attach_log_entry_str, attach_log_entry_stat, storage.format_version); - String attach_rollback_log_entry_barrier_path = fs::path(entry.znode_path) / ("log_" + entry.state.toString() + "_rollback"); - Coordination::Stat attach_rollback_log_entry_stat; - String attach_rollback_log_entry_str; - if (zk->tryGet(attach_rollback_log_entry_barrier_path, attach_rollback_log_entry_str, &attach_rollback_log_entry_stat)) - { - LOG_DEBUG(log, "Log entry was already created will check the existing one."); + Coordination::Requests ops; + ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); - attach_rollback_log_entry = *ReplicatedMergeTreeLogEntry::parse(attach_rollback_log_entry_str, - attach_rollback_log_entry_stat, - storage.format_version); - } - else - { - const auto attach_log_entry = ReplicatedMergeTreeLogEntry::parse(attach_log_entry_str, attach_log_entry_stat, - storage.format_version); + auto drop_part_info = MergeTreePartInfo::fromPartName(attach_log_entry->new_part_name, storage.format_version); - Coordination::Requests ops; - ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); + storage.getClearBlocksInPartitionOps( + ops, *zk, drop_part_info.partition_id, drop_part_info.min_block, drop_part_info.max_block); + size_t clear_block_ops_size = ops.size(); - auto drop_part_info = MergeTreePartInfo::fromPartName(attach_log_entry->new_part_name, storage.format_version); + attach_rollback_log_entry.type = ReplicatedMergeTreeLogEntryData::DROP_RANGE; + attach_rollback_log_entry.log_entry_id = attach_rollback_log_entry_barrier_path; + attach_rollback_log_entry.source_replica = storage.replica_name; + attach_rollback_log_entry.source_shard = zookeeper_path; - storage.getClearBlocksInPartitionOps( - ops, *zk, drop_part_info.partition_id, drop_part_info.min_block, drop_part_info.max_block); - size_t clear_block_ops_size = ops.size(); + attach_rollback_log_entry.new_part_name = getPartNamePossiblyFake(storage.format_version, drop_part_info); + attach_rollback_log_entry.create_time = time(nullptr); - attach_rollback_log_entry.type = ReplicatedMergeTreeLogEntryData::DROP_RANGE; - attach_rollback_log_entry.log_entry_id = attach_rollback_log_entry_barrier_path; - attach_rollback_log_entry.source_replica = storage.replica_name; - attach_rollback_log_entry.source_shard = zookeeper_path; - - attach_rollback_log_entry.new_part_name = getPartNamePossiblyFake(storage.format_version, drop_part_info); - attach_rollback_log_entry.create_time = time(nullptr); - - ops.emplace_back(zkutil::makeCreateRequest(attach_rollback_log_entry_barrier_path, attach_rollback_log_entry.toString(), -1)); - ops.emplace_back(zkutil::makeCreateRequest( - entry.to_shard + "/log/log-", attach_rollback_log_entry.toString(), zkutil::CreateMode::PersistentSequential)); - ops.emplace_back(zkutil::makeSetRequest(entry.to_shard + "/log", "", -1)); - Coordination::Responses responses; - Coordination::Error rc = zk->tryMulti(ops, responses); - zkutil::KeeperMultiException::check(rc, ops, responses); - - String log_znode_path - = dynamic_cast(*responses[clear_block_ops_size]).path_created; - attach_rollback_log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); - - LOG_DEBUG(log, "Pushed log entry: {}", log_znode_path); - } - - Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(entry.to_shard, attach_rollback_log_entry, 1); - if (!unwaited.empty()) - throw Exception(ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); - - entry.state = EntryState::DESTINATION_FETCH; - return entry; - } - } - else - { - /// There is a chance that attach on destination will fail and this task will be left in the queue forever. - - Coordination::Requests ops; - ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); - - auto part = storage.getActiveContainingPart(entry.part_name); - - /// Allocating block number in other replicas zookeeper path - /// TODO Maybe we can do better. - auto block_number_lock = storage.allocateBlockNumber(part->info.partition_id, zk, attach_log_entry_barrier_path, entry.to_shard); - - ReplicatedMergeTreeLogEntryData log_entry; - - if (block_number_lock) - { - auto block_number = block_number_lock->getNumber(); - - auto part_info = part->info; - part_info.min_block = block_number; - part_info.max_block = block_number; - part_info.level = 0; - part_info.mutation = 0; - - /// Attach log entry (all replicas already fetched part) - log_entry.type = ReplicatedMergeTreeLogEntryData::ATTACH_PART; - log_entry.log_entry_id = attach_log_entry_barrier_path; - log_entry.part_checksum = part->checksums.getTotalChecksumHex(); - log_entry.create_time = std::time(nullptr); - log_entry.new_part_name = part_info.getPartNameAndCheckFormat(storage.format_version); - - ops.emplace_back(zkutil::makeCreateRequest(attach_log_entry_barrier_path, log_entry.toString(), -1)); - ops.emplace_back(zkutil::makeSetRequest(entry.to_shard + "/log", "", -1)); + ops.emplace_back( + zkutil::makeCreateRequest(attach_rollback_log_entry_barrier_path, attach_rollback_log_entry.toString(), -1)); ops.emplace_back(zkutil::makeCreateRequest( - entry.to_shard + "/log/log-", log_entry.toString(), zkutil::CreateMode::PersistentSequential)); - + entry.to_shard + "/log/log-", attach_rollback_log_entry.toString(), zkutil::CreateMode::PersistentSequential)); + ops.emplace_back(zkutil::makeSetRequest(entry.to_shard + "/log", "", -1)); Coordination::Responses responses; Coordination::Error rc = zk->tryMulti(ops, responses); zkutil::KeeperMultiException::check(rc, ops, responses); - String log_znode_path = dynamic_cast(*responses.back()).path_created; - log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); + String log_znode_path + = dynamic_cast(*responses[clear_block_ops_size]).path_created; + attach_rollback_log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); LOG_DEBUG(log, "Pushed log entry: {}", log_znode_path); } - else - { - LOG_DEBUG(log, "Log entry was already created will check the existing one."); - Coordination::Stat stat; - String log_entry_str = zk->get(attach_log_entry_barrier_path, &stat); - log_entry = *ReplicatedMergeTreeLogEntry::parse(log_entry_str, stat, storage.format_version); - } - - Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(entry.to_shard, log_entry, 1); + Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(entry.to_shard, attach_rollback_log_entry, 1); if (!unwaited.empty()) - throw Exception(ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); + throw Exception( + ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); - - entry.dst_part_name = log_entry.new_part_name; - entry.state = EntryState::SOURCE_DROP_PRE_DELAY; + entry.state = EntryState::DESTINATION_FETCH; return entry; } + + /// There is a chance that attach on destination will fail and this task will be left in the queue forever. + + Coordination::Requests ops; + ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); + + auto part = storage.getActiveContainingPart(entry.part_name); + + /// Allocating block number in other replicas zookeeper path + /// TODO Maybe we can do better. + auto block_number_lock + = storage.allocateBlockNumber(part->info.partition_id, zk, attach_log_entry_barrier_path, entry.to_shard); + + ReplicatedMergeTreeLogEntryData log_entry; + + if (block_number_lock) + { + auto block_number = block_number_lock->getNumber(); + + auto part_info = part->info; + part_info.min_block = block_number; + part_info.max_block = block_number; + part_info.level = 0; + part_info.mutation = 0; + + /// Attach log entry (all replicas already fetched part) + log_entry.type = ReplicatedMergeTreeLogEntryData::ATTACH_PART; + log_entry.log_entry_id = attach_log_entry_barrier_path; + log_entry.part_checksum = part->checksums.getTotalChecksumHex(); + log_entry.create_time = std::time(nullptr); + log_entry.new_part_name = part_info.getPartNameAndCheckFormat(storage.format_version); + + ops.emplace_back(zkutil::makeCreateRequest(attach_log_entry_barrier_path, log_entry.toString(), -1)); + ops.emplace_back(zkutil::makeSetRequest(entry.to_shard + "/log", "", -1)); + ops.emplace_back(zkutil::makeCreateRequest( + entry.to_shard + "/log/log-", log_entry.toString(), zkutil::CreateMode::PersistentSequential)); + + Coordination::Responses responses; + Coordination::Error rc = zk->tryMulti(ops, responses); + zkutil::KeeperMultiException::check(rc, ops, responses); + + String log_znode_path = dynamic_cast(*responses.back()).path_created; + log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); + + LOG_DEBUG(log, "Pushed log entry: {}", log_znode_path); + } + else + { + LOG_DEBUG(log, "Log entry was already created will check the existing one."); + + Coordination::Stat stat; + String log_entry_str = zk->get(attach_log_entry_barrier_path, &stat); + log_entry = *ReplicatedMergeTreeLogEntry::parse(log_entry_str, stat, storage.format_version); + } + + Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(entry.to_shard, log_entry, 1); + if (!unwaited.empty()) + throw Exception( + ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); + + + entry.dst_part_name = log_entry.new_part_name; + entry.state = EntryState::SOURCE_DROP_PRE_DELAY; + return entry; } case EntryState::SOURCE_DROP_PRE_DELAY: @@ -530,97 +525,91 @@ PartMovesBetweenShardsOrchestrator::Entry PartMovesBetweenShardsOrchestrator::st entry.state = EntryState::DESTINATION_ATTACH; return entry; } - else - { - std::this_thread::sleep_for(std::chrono::seconds((*storage.getSettings())[MergeTreeSetting::part_moves_between_shards_delay_seconds])); - entry.state = EntryState::SOURCE_DROP; - return entry; - } + + std::this_thread::sleep_for(std::chrono::seconds((*storage.getSettings())[MergeTreeSetting::part_moves_between_shards_delay_seconds])); + entry.state = EntryState::SOURCE_DROP; + return entry; } case EntryState::SOURCE_DROP: { if (entry.rollback) throw Exception(ErrorCodes::LOGICAL_ERROR, "It is not possible to rollback from this state. This is a bug."); + + // Can't use dropPartImpl directly as we need additional zk ops to remember the log entry + // for subsequent retries. + + ReplicatedMergeTreeLogEntryData source_drop_log_entry; + + String source_drop_log_entry_barrier_path = fs::path(entry.znode_path) / ("log_" + entry.state.toString()); + Coordination::Stat source_drop_log_entry_stat; + String source_drop_log_entry_str; + if (zk->tryGet(source_drop_log_entry_barrier_path, source_drop_log_entry_str, &source_drop_log_entry_stat)) + { + LOG_DEBUG(log, "Log entry was already created will check the existing one."); + + source_drop_log_entry + = *ReplicatedMergeTreeLogEntry::parse(source_drop_log_entry_str, source_drop_log_entry_stat, storage.format_version); + } else { - // Can't use dropPartImpl directly as we need additional zk ops to remember the log entry - // for subsequent retries. + auto source_drop_part_info = MergeTreePartInfo::fromPartName(entry.part_name, storage.format_version); - ReplicatedMergeTreeLogEntryData source_drop_log_entry; + Coordination::Requests ops; + ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); - String source_drop_log_entry_barrier_path = fs::path(entry.znode_path) / ("log_" + entry.state.toString()); - Coordination::Stat source_drop_log_entry_stat; - String source_drop_log_entry_str; - if (zk->tryGet(source_drop_log_entry_barrier_path, source_drop_log_entry_str, &source_drop_log_entry_stat)) - { - LOG_DEBUG(log, "Log entry was already created will check the existing one."); + storage.getClearBlocksInPartitionOps( + ops, *zk, source_drop_part_info.partition_id, source_drop_part_info.min_block, source_drop_part_info.max_block); - source_drop_log_entry = *ReplicatedMergeTreeLogEntry::parse(source_drop_log_entry_str, source_drop_log_entry_stat, - storage.format_version); - } - else - { - auto source_drop_part_info = MergeTreePartInfo::fromPartName(entry.part_name, storage.format_version); + source_drop_log_entry.type = ReplicatedMergeTreeLogEntryData::DROP_RANGE; + source_drop_log_entry.log_entry_id = source_drop_log_entry_barrier_path; + source_drop_log_entry.create_time = std::time(nullptr); + source_drop_log_entry.new_part_name = getPartNamePossiblyFake(storage.format_version, source_drop_part_info); + source_drop_log_entry.source_replica = storage.replica_name; - Coordination::Requests ops; - ops.emplace_back(zkutil::makeCheckRequest(entry.znode_path, entry.version)); + ops.emplace_back(zkutil::makeCreateRequest(source_drop_log_entry_barrier_path, source_drop_log_entry.toString(), -1)); + ops.emplace_back(zkutil::makeSetRequest(zookeeper_path + "/log", "", -1)); + ops.emplace_back(zkutil::makeCreateRequest( + zookeeper_path + "/log/log-", source_drop_log_entry.toString(), zkutil::CreateMode::PersistentSequential)); - storage.getClearBlocksInPartitionOps(ops, *zk, source_drop_part_info.partition_id, source_drop_part_info.min_block, source_drop_part_info.max_block); + Coordination::Responses responses; + Coordination::Error rc = zk->tryMulti(ops, responses); + zkutil::KeeperMultiException::check(rc, ops, responses); - source_drop_log_entry.type = ReplicatedMergeTreeLogEntryData::DROP_RANGE; - source_drop_log_entry.log_entry_id = source_drop_log_entry_barrier_path; - source_drop_log_entry.create_time = std::time(nullptr); - source_drop_log_entry.new_part_name = getPartNamePossiblyFake(storage.format_version, source_drop_part_info); - source_drop_log_entry.source_replica = storage.replica_name; + String log_znode_path = dynamic_cast(*responses.back()).path_created; + source_drop_log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); - ops.emplace_back(zkutil::makeCreateRequest(source_drop_log_entry_barrier_path, source_drop_log_entry.toString(), -1)); - ops.emplace_back(zkutil::makeSetRequest(zookeeper_path + "/log", "", -1)); - ops.emplace_back(zkutil::makeCreateRequest( - zookeeper_path + "/log/log-", source_drop_log_entry.toString(), zkutil::CreateMode::PersistentSequential)); - - Coordination::Responses responses; - Coordination::Error rc = zk->tryMulti(ops, responses); - zkutil::KeeperMultiException::check(rc, ops, responses); - - String log_znode_path = dynamic_cast(*responses.back()).path_created; - source_drop_log_entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); - - LOG_DEBUG(log, "Pushed log entry: {}", log_znode_path); - } - - Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(zookeeper_path, source_drop_log_entry, 1); - if (!unwaited.empty()) - throw Exception(ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); - - entry.state = EntryState::SOURCE_DROP_POST_DELAY; - return entry; + LOG_DEBUG(log, "Pushed log entry: {}", log_znode_path); } + + Strings unwaited = storage.tryWaitForAllReplicasToProcessLogEntry(zookeeper_path, source_drop_log_entry, 1); + if (!unwaited.empty()) + throw Exception( + ErrorCodes::TIMEOUT_EXCEEDED, "Some replicas haven't processed event: {}, will retry later.", toString(unwaited)); + + entry.state = EntryState::SOURCE_DROP_POST_DELAY; + return entry; } case EntryState::SOURCE_DROP_POST_DELAY: { if (entry.rollback) throw Exception(ErrorCodes::LOGICAL_ERROR, "It is not possible to rollback from this state. This is a bug."); - else - { - std::this_thread::sleep_for(std::chrono::seconds((*storage.getSettings())[MergeTreeSetting::part_moves_between_shards_delay_seconds])); - entry.state = EntryState::REMOVE_UUID_PIN; - return entry; - } + + std::this_thread::sleep_for(std::chrono::seconds((*storage.getSettings())[MergeTreeSetting::part_moves_between_shards_delay_seconds])); + entry.state = EntryState::REMOVE_UUID_PIN; + return entry; } case EntryState::REMOVE_UUID_PIN: { if (entry.rollback) throw Exception(ErrorCodes::LOGICAL_ERROR, "It is not possible to rollback from this state. This is a bug."); - else - { - removePins(entry, zk); - entry.state = EntryState::DONE; - return entry; - } + removePins(entry, zk); + + entry.state = EntryState::DONE; + return entry; } } } @@ -683,13 +672,12 @@ CancellationCode PartMovesBetweenShardsOrchestrator::killPartMoveToShard(const U // Orchestrator will process it in background. return CancellationCode::CancelSent; } - else if (code == Coordination::Error::ZBADVERSION) + if (code == Coordination::Error::ZBADVERSION) { /// Node was updated meanwhile. We must re-read it and repeat all the actions. continue; } - else - throw Coordination::Exception::fromPath(code, entry.znode_path); + throw Coordination::Exception::fromPath(code, entry.znode_path); } } diff --git a/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.h b/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.h index abe259c77ab..6dfaa7d3886 100644 --- a/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.h +++ b/src/Storages/MergeTree/PartMovesBetweenShardsOrchestrator.h @@ -89,17 +89,27 @@ public: static EntryState::Value fromString(String in) { if (in == "TODO") return TODO; - else if (in == "SYNC_SOURCE") return SYNC_SOURCE; - else if (in == "SYNC_DESTINATION") return SYNC_DESTINATION; - else if (in == "DESTINATION_FETCH") return DESTINATION_FETCH; - else if (in == "DESTINATION_ATTACH") return DESTINATION_ATTACH; - else if (in == "SOURCE_DROP_PRE_DELAY") return SOURCE_DROP_PRE_DELAY; - else if (in == "SOURCE_DROP") return SOURCE_DROP; - else if (in == "SOURCE_DROP_POST_DELAY") return SOURCE_DROP_POST_DELAY; - else if (in == "REMOVE_UUID_PIN") return REMOVE_UUID_PIN; - else if (in == "DONE") return DONE; - else if (in == "CANCELLED") return CANCELLED; - else throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown state: {}", in); + if (in == "SYNC_SOURCE") + return SYNC_SOURCE; + if (in == "SYNC_DESTINATION") + return SYNC_DESTINATION; + if (in == "DESTINATION_FETCH") + return DESTINATION_FETCH; + if (in == "DESTINATION_ATTACH") + return DESTINATION_ATTACH; + if (in == "SOURCE_DROP_PRE_DELAY") + return SOURCE_DROP_PRE_DELAY; + if (in == "SOURCE_DROP") + return SOURCE_DROP; + if (in == "SOURCE_DROP_POST_DELAY") + return SOURCE_DROP_POST_DELAY; + if (in == "REMOVE_UUID_PIN") + return REMOVE_UUID_PIN; + if (in == "DONE") + return DONE; + if (in == "CANCELLED") + return CANCELLED; + throw Exception(ErrorCodes::LOGICAL_ERROR, "Unknown state: {}", in); } }; diff --git a/src/Storages/MergeTree/RPNBuilder.cpp b/src/Storages/MergeTree/RPNBuilder.cpp index 056440fcda1..8a74d189de7 100644 --- a/src/Storages/MergeTree/RPNBuilder.cpp +++ b/src/Storages/MergeTree/RPNBuilder.cpp @@ -134,8 +134,8 @@ std::string RPNBuilderTreeNode::getColumnName() const { if (ast_node) return ast_node->getColumnNameWithoutAlias(); - else - return getColumnNameWithoutAlias(*dag_node, getTreeContext().getSettings()[Setting::allow_experimental_analyzer]); + + return getColumnNameWithoutAlias(*dag_node, getTreeContext().getSettings()[Setting::allow_experimental_analyzer]); } std::string RPNBuilderTreeNode::getColumnNameWithModuloLegacy() const @@ -146,10 +146,8 @@ std::string RPNBuilderTreeNode::getColumnNameWithModuloLegacy() const KeyDescription::moduloToModuloLegacyRecursive(adjusted_ast); return adjusted_ast->getColumnNameWithoutAlias(); } - else - { - return getColumnNameWithoutAlias(*dag_node, getTreeContext().getSettings()[Setting::allow_experimental_analyzer], true /*legacy*/); - } + + return getColumnNameWithoutAlias(*dag_node, getTreeContext().getSettings()[Setting::allow_experimental_analyzer], true /*legacy*/); } bool RPNBuilderTreeNode::isFunction() const @@ -158,11 +156,9 @@ bool RPNBuilderTreeNode::isFunction() const { return typeid_cast(ast_node); } - else - { - const auto * node_without_alias = getNodeWithoutAlias(dag_node); - return node_without_alias->type == ActionsDAG::ActionType::FUNCTION; - } + + const auto * node_without_alias = getNodeWithoutAlias(dag_node); + return node_without_alias->type == ActionsDAG::ActionType::FUNCTION; } bool RPNBuilderTreeNode::isConstant() const @@ -181,11 +177,9 @@ bool RPNBuilderTreeNode::isConstant() const return false; } - else - { - const auto * node_without_alias = getNodeWithoutAlias(dag_node); - return node_without_alias->column && isColumnConst(*node_without_alias->column); - } + + const auto * node_without_alias = getNodeWithoutAlias(dag_node); + return node_without_alias->column && isColumnConst(*node_without_alias->column); } bool RPNBuilderTreeNode::isSubqueryOrSet() const @@ -196,11 +190,9 @@ bool RPNBuilderTreeNode::isSubqueryOrSet() const typeid_cast(ast_node) || typeid_cast(ast_node); } - else - { - const auto * node_without_alias = getNodeWithoutAlias(dag_node); - return node_without_alias->result_type->getTypeId() == TypeIndex::Set; - } + + const auto * node_without_alias = getNodeWithoutAlias(dag_node); + return node_without_alias->result_type->getTypeId() == TypeIndex::Set; } ColumnWithTypeAndName RPNBuilderTreeNode::getConstantColumn() const @@ -226,12 +218,10 @@ ColumnWithTypeAndName RPNBuilderTreeNode::getConstantColumn() const return block_with_constants.getByName(column_name); } - else - { - const auto * node_without_alias = getNodeWithoutAlias(dag_node); - result.type = node_without_alias->result_type; - result.column = node_without_alias->column; - } + + const auto * node_without_alias = getNodeWithoutAlias(dag_node); + result.type = node_without_alias->result_type; + result.column = node_without_alias->column; return result; } @@ -262,8 +252,7 @@ bool RPNBuilderTreeNode::tryGetConstant(Field & output_value, DataTypePtr & outp return true; } - else if (block_with_constants.has(column_name) && - isColumnConst(*block_with_constants.getByName(column_name).column)) + if (block_with_constants.has(column_name) && isColumnConst(*block_with_constants.getByName(column_name).column)) { /// An expression which is dependent on constants only const auto & constant_column = block_with_constants.getByName(column_name); @@ -329,7 +318,7 @@ FutureSetPtr RPNBuilderTreeNode::tryGetPreparedSet() const return prepared_sets->findSubquery(key); } - else if (dag_node) + if (dag_node) { const auto * node_without_alias = getNodeWithoutAlias(dag_node); return tryGetSetFromDAGNode(node_without_alias); @@ -349,7 +338,7 @@ FutureSetPtr RPNBuilderTreeNode::tryGetPreparedSet(const DataTypes & data_types) return prepared_sets->findTuple(ast_node->getTreeHash(/*ignore_aliases=*/ true), data_types); } - else if (dag_node) + if (dag_node) { const auto * node_without_alias = getNodeWithoutAlias(dag_node); return tryGetSetFromDAGNode(node_without_alias); @@ -365,8 +354,7 @@ RPNBuilderFunctionTreeNode RPNBuilderTreeNode::toFunctionNode() const if (ast_node) return RPNBuilderFunctionTreeNode(ast_node, tree_context); - else - return RPNBuilderFunctionTreeNode(getNodeWithoutAlias(dag_node), tree_context); + return RPNBuilderFunctionTreeNode(getNodeWithoutAlias(dag_node), tree_context); } std::optional RPNBuilderTreeNode::toFunctionNodeOrNull() const @@ -376,16 +364,14 @@ std::optional RPNBuilderTreeNode::toFunctionNodeOrNu if (ast_node) return RPNBuilderFunctionTreeNode(this->ast_node, tree_context); - else - return RPNBuilderFunctionTreeNode(getNodeWithoutAlias(dag_node), tree_context); + return RPNBuilderFunctionTreeNode(getNodeWithoutAlias(dag_node), tree_context); } std::string RPNBuilderFunctionTreeNode::getFunctionName() const { if (ast_node) return assert_cast(ast_node)->name; - else - return dag_node->function_base->getName(); + return dag_node->function_base->getName(); } size_t RPNBuilderFunctionTreeNode::getArgumentsSize() const @@ -395,19 +381,17 @@ size_t RPNBuilderFunctionTreeNode::getArgumentsSize() const const auto * ast_function = assert_cast(ast_node); return ast_function->arguments ? ast_function->arguments->children.size() : 0; } - else - { - // indexHint arguments are stored inside of `FunctionIndexHint` class, - // because they are used only for index analysis. - if (dag_node->function_base->getName() == "indexHint") - { - const auto * adaptor = typeid_cast(dag_node->function_base.get()); - const auto * index_hint = typeid_cast(adaptor->getFunction().get()); - return index_hint->getActions().getOutputs().size(); - } - return dag_node->children.size(); + // indexHint arguments are stored inside of `FunctionIndexHint` class, + // because they are used only for index analysis. + if (dag_node->function_base->getName() == "indexHint") + { + const auto * adaptor = typeid_cast(dag_node->function_base.get()); + const auto * index_hint = typeid_cast(adaptor->getFunction().get()); + return index_hint->getActions().getOutputs().size(); } + + return dag_node->children.size(); } RPNBuilderTreeNode RPNBuilderFunctionTreeNode::getArgumentAt(size_t index) const @@ -423,19 +407,17 @@ RPNBuilderTreeNode RPNBuilderFunctionTreeNode::getArgumentAt(size_t index) const const auto * ast_function = assert_cast(ast_node); return RPNBuilderTreeNode(ast_function->arguments->children[index].get(), tree_context); } - else + + // indexHint arguments are stored inside of `FunctionIndexHint` class, + // because they are used only for index analysis. + if (dag_node->function_base->getName() == "indexHint") { - // indexHint arguments are stored inside of `FunctionIndexHint` class, - // because they are used only for index analysis. - if (dag_node->function_base->getName() == "indexHint") - { - const auto & adaptor = typeid_cast(*dag_node->function_base); - const auto & index_hint = typeid_cast(*adaptor.getFunction()); - return RPNBuilderTreeNode(index_hint.getActions().getOutputs()[index], tree_context); - } - - return RPNBuilderTreeNode(dag_node->children[index], tree_context); + const auto & adaptor = typeid_cast(*dag_node->function_base); + const auto & index_hint = typeid_cast(*adaptor.getFunction()); + return RPNBuilderTreeNode(index_hint.getActions().getOutputs()[index], tree_context); } + + return RPNBuilderTreeNode(dag_node->children[index], tree_context); } } diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp index bb7d683023b..8342fbed8b9 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp +++ b/src/Storages/MergeTree/ReplicatedMergeTreeCleanupThread.cpp @@ -386,10 +386,9 @@ size_t ReplicatedMergeTreeCleanupThread::clearOldLogs() /// Another replica already deleted the same node concurrently. break; } - else - { - zkutil::KeeperMultiException::check(e, ops, responses); - } + + zkutil::KeeperMultiException::check(e, ops, responses); + ops.clear(); } } diff --git a/src/Storages/MergeTree/ReplicatedMergeTreePartCheckThread.cpp b/src/Storages/MergeTree/ReplicatedMergeTreePartCheckThread.cpp index bb85e224c1f..932463140a1 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreePartCheckThread.cpp +++ b/src/Storages/MergeTree/ReplicatedMergeTreePartCheckThread.cpp @@ -613,7 +613,7 @@ void ReplicatedMergeTreePartCheckThread::run() { throw Exception(ErrorCodes::LOGICAL_ERROR, "Someone erased checking part from parts_queue. This is a bug."); } - else if (recheck_after.has_value()) + if (recheck_after.has_value()) { LOG_TRACE(log, "Will recheck part {} after after {}s", selected->name, *recheck_after); selected->time = std::chrono::steady_clock::now() + std::chrono::seconds(*recheck_after); diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp b/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp index b1e7020f117..6b1581645f8 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp +++ b/src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp @@ -1797,17 +1797,14 @@ ReplicatedMergeTreeQueue::SelectedEntryPtr ReplicatedMergeTreeQueue::selectEntry queue.splice(queue.end(), queue, it); break; } - else - { - ++(*it)->num_postponed; - (*it)->last_postpone_time = time(nullptr); - } + + ++(*it)->num_postponed; + (*it)->last_postpone_time = time(nullptr); } if (entry) return std::make_shared(entry, std::unique_ptr{new CurrentlyExecuting(entry, *this, lock)}); - else - return {}; + return {}; } @@ -2162,8 +2159,7 @@ bool ReplicatedMergeTreeQueue::tryFinalizeMutations(zkutil::ZooKeeperPtr zookeep if (candidates.empty()) return false; - else - LOG_DEBUG(log, "Trying to finalize {} mutations", candidates.size()); + LOG_DEBUG(log, "Trying to finalize {} mutations", candidates.size()); /// We need to check committing block numbers and new parts which could be committed. /// Actually we don't need most of predicate logic here but it all the code related to committing blocks @@ -2493,8 +2489,7 @@ bool BaseMergePredicate::operator()( { if (left) return canMergeTwoParts(left, right, out_reason); - else - return canMergeSinglePart(right, out_reason); + return canMergeSinglePart(right, out_reason); } template @@ -2838,11 +2833,9 @@ bool ReplicatedMergeTreeMergePredicate::isMutationFinished(const std::string & z LOG_TRACE(queue.log, "Mutation {} is not done because some parts [{}] were just committed", znode_name, fmt::join(it->second.parts_to_do.getParts(), ", ")); return false; } - else - { - LOG_TRACE(queue.log, "Mutation {} is done because it doesn't exist anymore", znode_name); - return true; - } + + LOG_TRACE(queue.log, "Mutation {} is done because it doesn't exist anymore", znode_name); + return true; } bool ReplicatedMergeTreeMergePredicate::isGoingToBeDropped(const MergeTreePartInfo & new_drop_range_info, diff --git a/src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp b/src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp index 1321af1e804..95469337f8a 100644 --- a/src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp +++ b/src/Storages/MergeTree/ReplicatedMergeTreeSink.cpp @@ -1009,21 +1009,19 @@ std::pair, bool> ReplicatedMergeTreeSinkImpl:: block_number_lock->assumeUnlocked(); return CommitRetryContext::SUCCESS; } - else - { - LOG_DEBUG(log, "Insert of part {} was not committed to keeper. Will try again with a new block", part->name); - /// We checked in keeper and the the data in ops being written so we can retry the process again, but - /// there is a caveat: as we lost the connection the block number that we got (EphemeralSequential) - /// might or might not be there (and it belongs to a different session anyway) so we need to assume - /// it's not there and will be removed automatically, and start from scratch - /// In order to start from scratch we need to undo the changes that we've done as part of the - /// transaction: renameTempPartAndAdd - transaction.rollbackPartsToTemporaryState(); - part->is_temp = true; - part->renameTo(temporary_part_relative_path, false); - /// Throw an exception to set the proper keeper error and force a retry (if possible) - zkutil::KeeperMultiException::check(multi_code, ops, responses); - } + + LOG_DEBUG(log, "Insert of part {} was not committed to keeper. Will try again with a new block", part->name); + /// We checked in keeper and the the data in ops being written so we can retry the process again, but + /// there is a caveat: as we lost the connection the block number that we got (EphemeralSequential) + /// might or might not be there (and it belongs to a different session anyway) so we need to assume + /// it's not there and will be removed automatically, and start from scratch + /// In order to start from scratch we need to undo the changes that we've done as part of the + /// transaction: renameTempPartAndAdd + transaction.rollbackPartsToTemporaryState(); + part->is_temp = true; + part->renameTo(temporary_part_relative_path, false); + /// Throw an exception to set the proper keeper error and force a retry (if possible) + zkutil::KeeperMultiException::check(multi_code, ops, responses); } transaction.rollback(); diff --git a/src/Storages/MergeTree/VectorSimilarityCondition.cpp b/src/Storages/MergeTree/VectorSimilarityCondition.cpp index 13dc6abfbf6..ea3b1fbad8d 100644 --- a/src/Storages/MergeTree/VectorSimilarityCondition.cpp +++ b/src/Storages/MergeTree/VectorSimilarityCondition.cpp @@ -48,10 +48,9 @@ VectorSimilarityCondition::Info::DistanceFunction stringToDistanceFunction(const { if (distance_function == "L2Distance") return VectorSimilarityCondition::Info::DistanceFunction::L2; - else if (distance_function == "cosineDistance") + if (distance_function == "cosineDistance") return VectorSimilarityCondition::Info::DistanceFunction::Cosine; - else - return VectorSimilarityCondition::Info::DistanceFunction::Unknown; + return VectorSimilarityCondition::Info::DistanceFunction::Unknown; } } @@ -184,7 +183,7 @@ bool VectorSimilarityCondition::traverseAtomAST(const ASTPtr & node, RPNElement return true; } /// Match identifier - else if (const auto * identifier = node->as()) + if (const auto * identifier = node->as()) { out.function = RPNElement::FUNCTION_IDENTIFIER; out.identifier.emplace(identifier->name()); diff --git a/src/Storages/MergeTree/registerStorageMergeTree.cpp b/src/Storages/MergeTree/registerStorageMergeTree.cpp index 14cd7e897f2..b16fa7b88a4 100644 --- a/src/Storages/MergeTree/registerStorageMergeTree.cpp +++ b/src/Storages/MergeTree/registerStorageMergeTree.cpp @@ -75,10 +75,8 @@ static Names extractColumnNames(const ASTPtr & node) return res; } - else - { - return {getIdentifierName(node)}; - } + + return {getIdentifierName(node)}; } constexpr auto verbose_help_message = R"( @@ -240,10 +238,12 @@ static TableZnodeInfo extractZooKeeperPathAndReplicaNameFromEngineArgs( "specify them explicitly, enable setting " "database_replicated_allow_replicated_engine_arguments."); } - else if (!query.attach && is_replicated_database && local_context->getSettingsRef()[Setting::database_replicated_allow_replicated_engine_arguments] == 1) + if (!query.attach && is_replicated_database && local_context->getSettingsRef()[Setting::database_replicated_allow_replicated_engine_arguments] == 1) { - LOG_WARNING(&Poco::Logger::get("registerStorageMergeTree"), "It's not recommended to explicitly specify " - "zookeeper_path and replica_name in ReplicatedMergeTree arguments"); + LOG_WARNING( + &Poco::Logger::get("registerStorageMergeTree"), + "It's not recommended to explicitly specify " + "zookeeper_path and replica_name in ReplicatedMergeTree arguments"); } /// Get path and name from engine arguments @@ -265,7 +265,7 @@ static TableZnodeInfo extractZooKeeperPathAndReplicaNameFromEngineArgs( return expand_macro(ast_zk_path, ast_replica_name, ast_zk_path->value.safeGet(), ast_replica_name->value.safeGet()); } - else if (is_extended_storage_def + if (is_extended_storage_def && (arg_cnt == 0 || !engine_args[arg_num]->as() || (arg_cnt == 1 && (getNamePart(engine_name) == "Graphite")))) @@ -291,8 +291,8 @@ static TableZnodeInfo extractZooKeeperPathAndReplicaNameFromEngineArgs( return res; } - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Expected two string literal arguments: zookeeper_path and replica_name"); + + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Expected two string literal arguments: zookeeper_path and replica_name"); } /// Extracts a zookeeper path from a specified CREATE TABLE query. @@ -474,11 +474,14 @@ static StoragePtr create(const StorageFactory::Arguments & args) if (is_extended_storage_def) throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "With extended storage definition syntax storage {} requires {}{}", args.engine_name, msg, verbose_help_message); - else - throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "ORDER BY or PRIMARY KEY clause is missing. " - "Consider using extended storage definition syntax with ORDER BY or PRIMARY KEY clause. " - "With deprecated old syntax (highly not recommended) storage {} requires {}{}", - args.engine_name, msg, verbose_help_message); + throw Exception( + ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, + "ORDER BY or PRIMARY KEY clause is missing. " + "Consider using extended storage definition syntax with ORDER BY or PRIMARY KEY clause. " + "With deprecated old syntax (highly not recommended) storage {} requires {}{}", + args.engine_name, + msg, + verbose_help_message); } if (is_extended_storage_def) @@ -833,16 +836,15 @@ static StoragePtr create(const StorageFactory::Arguments & args) std::move(storage_settings), need_check_table_structure); } - else - return std::make_shared( - args.table_id, - args.relative_data_path, - metadata, - args.mode, - context, - date_column_name, - merging_params, - std::move(storage_settings)); + return std::make_shared( + args.table_id, + args.relative_data_path, + metadata, + args.mode, + context, + date_column_name, + merging_params, + std::move(storage_settings)); } diff --git a/src/Storages/MutationCommands.cpp b/src/Storages/MutationCommands.cpp index 719ebb06ec7..a3053ac97be 100644 --- a/src/Storages/MutationCommands.cpp +++ b/src/Storages/MutationCommands.cpp @@ -43,7 +43,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, res.partition = command->partition->clone(); return res; } - else if (command->type == ASTAlterCommand::UPDATE) + if (command->type == ASTAlterCommand::UPDATE) { MutationCommand res; res.ast = command->ptr(); @@ -56,13 +56,14 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, const auto & assignment = assignment_ast->as(); auto insertion = res.column_to_update_expression.emplace(assignment.column_name, assignment.expression()); if (!insertion.second) - throw Exception(ErrorCodes::MULTIPLE_ASSIGNMENTS_TO_COLUMN, - "Multiple assignments in the single statement to column {}", - backQuote(assignment.column_name)); + throw Exception( + ErrorCodes::MULTIPLE_ASSIGNMENTS_TO_COLUMN, + "Multiple assignments in the single statement to column {}", + backQuote(assignment.column_name)); } return res; } - else if (command->type == ASTAlterCommand::APPLY_DELETED_MASK) + if (command->type == ASTAlterCommand::APPLY_DELETED_MASK) { MutationCommand res; res.ast = command->ptr(); @@ -73,7 +74,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, res.partition = command->partition->clone(); return res; } - else if (command->type == ASTAlterCommand::MATERIALIZE_INDEX) + if (command->type == ASTAlterCommand::MATERIALIZE_INDEX) { MutationCommand res; res.ast = command->ptr(); @@ -84,7 +85,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, res.index_name = command->index->as().name(); return res; } - else if (command->type == ASTAlterCommand::MATERIALIZE_STATISTICS) + if (command->type == ASTAlterCommand::MATERIALIZE_STATISTICS) { MutationCommand res; res.ast = command->ptr(); @@ -95,7 +96,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, res.statistics_columns = command->statistics_decl->as().getColumnNames(); return res; } - else if (command->type == ASTAlterCommand::MATERIALIZE_PROJECTION) + if (command->type == ASTAlterCommand::MATERIALIZE_PROJECTION) { MutationCommand res; res.ast = command->ptr(); @@ -106,7 +107,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, res.projection_name = command->projection->as().name(); return res; } - else if (command->type == ASTAlterCommand::MATERIALIZE_COLUMN) + if (command->type == ASTAlterCommand::MATERIALIZE_COLUMN) { MutationCommand res; res.ast = command->ptr(); @@ -118,8 +119,8 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, } /// MODIFY COLUMN x REMOVE MATERIALIZED/RESET SETTING/MODIFY SETTING is a valid alter command, but doesn't have any specified column type, /// thus no mutation is needed - else if ( - parse_alter_commands && command->type == ASTAlterCommand::MODIFY_COLUMN && command->remove_property.empty() && nullptr == command->settings_changes && nullptr == command->settings_resets) + if (parse_alter_commands && command->type == ASTAlterCommand::MODIFY_COLUMN && command->remove_property.empty() + && nullptr == command->settings_changes && nullptr == command->settings_resets) { MutationCommand res; res.ast = command->ptr(); @@ -131,7 +132,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, res.data_type = DataTypeFactory::instance().get(ast_col_decl.type); return res; } - else if (parse_alter_commands && command->type == ASTAlterCommand::DROP_COLUMN) + if (parse_alter_commands && command->type == ASTAlterCommand::DROP_COLUMN) { MutationCommand res; res.ast = command->ptr(); @@ -144,7 +145,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, return res; } - else if (parse_alter_commands && command->type == ASTAlterCommand::DROP_INDEX) + if (parse_alter_commands && command->type == ASTAlterCommand::DROP_INDEX) { MutationCommand res; res.ast = command->ptr(); @@ -156,7 +157,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, res.clear = true; return res; } - else if (parse_alter_commands && command->type == ASTAlterCommand::DROP_STATISTICS) + if (parse_alter_commands && command->type == ASTAlterCommand::DROP_STATISTICS) { MutationCommand res; res.ast = command->ptr(); @@ -168,7 +169,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, res.statistics_columns = command->statistics_decl->as().getColumnNames(); return res; } - else if (parse_alter_commands && command->type == ASTAlterCommand::DROP_PROJECTION) + if (parse_alter_commands && command->type == ASTAlterCommand::DROP_PROJECTION) { MutationCommand res; res.ast = command->ptr(); @@ -180,7 +181,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, res.clear = true; return res; } - else if (parse_alter_commands && command->type == ASTAlterCommand::RENAME_COLUMN) + if (parse_alter_commands && command->type == ASTAlterCommand::RENAME_COLUMN) { MutationCommand res; res.ast = command->ptr(); @@ -189,7 +190,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, res.rename_to = command->rename_to->as().name(); return res; } - else if (command->type == ASTAlterCommand::MATERIALIZE_TTL) + if (command->type == ASTAlterCommand::MATERIALIZE_TTL) { MutationCommand res; res.ast = command->ptr(); @@ -198,13 +199,11 @@ std::optional MutationCommand::parse(ASTAlterCommand * command, res.partition = command->partition->clone(); return res; } - else - { - MutationCommand res; - res.ast = command->ptr(); - res.type = ALTER_WITHOUT_MUTATION; - return res; - } + + MutationCommand res; + res.ast = command->ptr(); + res.type = ALTER_WITHOUT_MUTATION; + return res; } diff --git a/src/Storages/NATS/NATSSource.cpp b/src/Storages/NATS/NATSSource.cpp index 40068be92d4..23ee0da0642 100644 --- a/src/Storages/NATS/NATSSource.cpp +++ b/src/Storages/NATS/NATSSource.cpp @@ -126,10 +126,8 @@ Chunk NATSSource::generate() return 1; } - else - { - throw std::move(e); - } + + throw std::move(e); }; StreamingFormatExecutor executor(non_virtual_header, input_format, on_error); diff --git a/src/Storages/NATS/StorageNATS.cpp b/src/Storages/NATS/StorageNATS.cpp index 8051189ca33..01c6570d095 100644 --- a/src/Storages/NATS/StorageNATS.cpp +++ b/src/Storages/NATS/StorageNATS.cpp @@ -174,8 +174,7 @@ String StorageNATS::getTableBasedName(String name, const StorageID & table_id) { if (name.empty()) return fmt::format("{}_{}", table_id.database_name, table_id.table_name); - else - return fmt::format("{}_{}_{}", name, table_id.database_name, table_id.table_name); + return fmt::format("{}_{}_{}", name, table_id.database_name, table_id.table_name); } @@ -400,10 +399,8 @@ SinkToStoragePtr StorageNATS::write(const ASTPtr &, const StorageMetadataPtr & m "This NATS engine reads from multiple subjects. " "You must specify `stream_like_engine_insert_queue` to choose the subject to write to"); } - else - { - subject = subjects[0]; - } + + subject = subjects[0]; } auto pos = subject.find('*'); @@ -733,10 +730,9 @@ bool StorageNATS::streamToViews() LOG_TRACE(log, "Reschedule streaming. Queues are empty."); return true; } - else - { - startLoop(); - } + + startLoop(); + /// Do not reschedule, do not stop event loop. return false; diff --git a/src/Storages/NamedCollectionsHelpers.cpp b/src/Storages/NamedCollectionsHelpers.cpp index eb4cb317f49..3b6b467430d 100644 --- a/src/Storages/NamedCollectionsHelpers.cpp +++ b/src/Storages/NamedCollectionsHelpers.cpp @@ -140,7 +140,7 @@ MutableNamedCollectionPtr tryGetNamedCollectionWithOverrides( // if allow_override_by_default is false we don't allow extra arguments throw Exception(ErrorCodes::BAD_ARGUMENTS, "Override not allowed because setting allow_override_by_default is disabled"); } - else if (!collection_copy->isOverridable(value_override->first, allow_override_by_default)) + if (!collection_copy->isOverridable(value_override->first, allow_override_by_default)) throw Exception(ErrorCodes::BAD_ARGUMENTS, "Override not allowed for '{}'", value_override->first); if (const ASTPtr * value = std::get_if(&value_override->second)) diff --git a/src/Storages/ObjectStorage/Azure/Configuration.cpp b/src/Storages/ObjectStorage/Azure/Configuration.cpp index 5536fa02683..d08e0d9debc 100644 --- a/src/Storages/ObjectStorage/Azure/Configuration.cpp +++ b/src/Storages/ObjectStorage/Azure/Configuration.cpp @@ -256,16 +256,14 @@ void StorageAzureConfiguration::fromAST(ASTs & engine_args, ContextPtr context, { throw Exception(ErrorCodes::BAD_ARGUMENTS, "Format and compression must be last arguments"); } - else - { - account_name = fourth_arg; - account_key = checkAndGetLiteralArgument(engine_args[4], "account_key"); - auto sixth_arg = checkAndGetLiteralArgument(engine_args[5], "format/account_name"); - if (!is_format_arg(sixth_arg)) - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown format {}", sixth_arg); - format = sixth_arg; - compression_method = checkAndGetLiteralArgument(engine_args[6], "compression"); - } + + account_name = fourth_arg; + account_key = checkAndGetLiteralArgument(engine_args[4], "account_key"); + auto sixth_arg = checkAndGetLiteralArgument(engine_args[5], "format/account_name"); + if (!is_format_arg(sixth_arg)) + throw Exception(ErrorCodes::BAD_ARGUMENTS, "Unknown format {}", sixth_arg); + format = sixth_arg; + compression_method = checkAndGetLiteralArgument(engine_args[6], "compression"); } else if (with_structure && engine_args.size() == 8) { diff --git a/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadata.cpp b/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadata.cpp index f04e868ee5a..98b181d04fa 100644 --- a/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadata.cpp +++ b/src/Storages/ObjectStorage/DataLakes/DeltaLakeMetadata.cpp @@ -205,7 +205,7 @@ struct DeltaLakeMetadataImpl Poco::JSON::Parser parser; Poco::Dynamic::Var json = parser.parse(json_str); - Poco::JSON::Object::Ptr object = json.extract(); + const Poco::JSON::Object::Ptr & object = json.extract(); if (!object) throw Exception(ErrorCodes::LOGICAL_ERROR, "Failed to parse metadata file"); @@ -353,33 +353,33 @@ struct DeltaLakeMetadataImpl WhichDataType which(check_type->getTypeId()); if (which.isStringOrFixedString()) return value; - else if (isBool(check_type)) + if (isBool(check_type)) return parse(value); - else if (which.isInt8()) + if (which.isInt8()) return parse(value); - else if (which.isUInt8()) + if (which.isUInt8()) return parse(value); - else if (which.isInt16()) + if (which.isInt16()) return parse(value); - else if (which.isUInt16()) + if (which.isUInt16()) return parse(value); - else if (which.isInt32()) + if (which.isInt32()) return parse(value); - else if (which.isUInt32()) + if (which.isUInt32()) return parse(value); - else if (which.isInt64()) + if (which.isInt64()) return parse(value); - else if (which.isUInt64()) + if (which.isUInt64()) return parse(value); - else if (which.isFloat32()) + if (which.isFloat32()) return parse(value); - else if (which.isFloat64()) + if (which.isFloat64()) return parse(value); - else if (which.isDate()) + if (which.isDate()) return UInt16{LocalDate{std::string(value)}.getDayNum()}; - else if (which.isDate32()) + if (which.isDate32()) return Int32{LocalDate{std::string(value)}.getExtenedDayNum()}; - else if (which.isDateTime64()) + if (which.isDateTime64()) { ReadBufferFromString in(value); DateTime64 time = 0; diff --git a/src/Storages/ObjectStorage/DataLakes/IStorageDataLake.h b/src/Storages/ObjectStorage/DataLakes/IStorageDataLake.h index 6dff60aeaa9..91fd9a9f981 100644 --- a/src/Storages/ObjectStorage/DataLakes/IStorageDataLake.h +++ b/src/Storages/ObjectStorage/DataLakes/IStorageDataLake.h @@ -86,14 +86,11 @@ public: { return ColumnsDescription(std::move(schema_from_metadata)); } - else - { - ConfigurationPtr configuration = base_configuration->clone(); - configuration->setPaths(metadata->getDataFiles()); - std::string sample_path; - return Storage::resolveSchemaFromData( - object_storage_, configuration, format_settings_, sample_path, local_context); - } + + ConfigurationPtr configuration = base_configuration->clone(); + configuration->setPaths(metadata->getDataFiles()); + std::string sample_path; + return Storage::resolveSchemaFromData(object_storage_, configuration, format_settings_, sample_path, local_context); } void updateConfiguration(ContextPtr local_context) override diff --git a/src/Storages/ObjectStorage/DataLakes/IcebergMetadata.cpp b/src/Storages/ObjectStorage/DataLakes/IcebergMetadata.cpp index ffc4dd09a3a..a7740db4e0f 100644 --- a/src/Storages/ObjectStorage/DataLakes/IcebergMetadata.cpp +++ b/src/Storages/ObjectStorage/DataLakes/IcebergMetadata.cpp @@ -395,7 +395,7 @@ DataLakeMetadataPtr IcebergMetadata::create( Poco::JSON::Parser parser; /// For some reason base/base/JSON.h can not parse this json file Poco::Dynamic::Var json = parser.parse(json_str); - Poco::JSON::Object::Ptr object = json.extract(); + const Poco::JSON::Object::Ptr & object = json.extract(); auto format_version = object->getValue("format-version"); auto [schema, schema_id] diff --git a/src/Storages/ObjectStorage/HDFS/AsynchronousReadBufferFromHDFS.cpp b/src/Storages/ObjectStorage/HDFS/AsynchronousReadBufferFromHDFS.cpp index 3bbc4e8a2ea..5f57a4714f1 100644 --- a/src/Storages/ObjectStorage/HDFS/AsynchronousReadBufferFromHDFS.cpp +++ b/src/Storages/ObjectStorage/HDFS/AsynchronousReadBufferFromHDFS.cpp @@ -203,7 +203,7 @@ off_t AsynchronousReadBufferFromHDFS::seek(off_t offset, int whence) assert(pos <= working_buffer.end()); return new_pos; } - else if (prefetch_future.valid()) + if (prefetch_future.valid()) { /// Read from prefetch buffer and recheck if the new position is valid inside. /// TODO we can judge quickly without waiting for prefetch diff --git a/src/Storages/ObjectStorage/HDFS/HDFSCommon.cpp b/src/Storages/ObjectStorage/HDFS/HDFSCommon.cpp index 7f8727eea1c..c1eb63cf715 100644 --- a/src/Storages/ObjectStorage/HDFS/HDFSCommon.cpp +++ b/src/Storages/ObjectStorage/HDFS/HDFSCommon.cpp @@ -59,29 +59,35 @@ void HDFSBuilderWrapper::loadFromConfig( #endif // USE_KRB5 continue; } - else if (key == "hadoop_kerberos_principal") + if (key == "hadoop_kerberos_principal") { #if USE_KRB5 need_kinit = true; hadoop_kerberos_principal = config.getString(key_path); hdfsBuilderSetPrincipal(hdfs_builder, hadoop_kerberos_principal.c_str()); #else // USE_KRB5 - LOG_WARNING(getLogger("HDFSClient"), "hadoop_kerberos_principal parameter is ignored because ClickHouse was built without support of krb5 library."); + LOG_WARNING( + getLogger("HDFSClient"), + "hadoop_kerberos_principal parameter is ignored because ClickHouse was built without support of krb5 library."); #endif // USE_KRB5 continue; } - else if (key == "hadoop_security_kerberos_ticket_cache_path") + if (key == "hadoop_security_kerberos_ticket_cache_path") { #if USE_KRB5 if (isUser) { - throw Exception(ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG, "hadoop.security.kerberos.ticket.cache.path cannot be set per user"); + throw Exception( + ErrorCodes::EXCESSIVE_ELEMENT_IN_CONFIG, "hadoop.security.kerberos.ticket.cache.path cannot be set per user"); } hadoop_security_kerberos_ticket_cache_path = config.getString(key_path); - // standard param - pass further + // standard param - pass further #else // USE_KRB5 - LOG_WARNING(getLogger("HDFSClient"), "hadoop.security.kerberos.ticket.cache.path parameter is ignored because ClickHouse was built without support of krb5 library."); + LOG_WARNING( + getLogger("HDFSClient"), + "hadoop.security.kerberos.ticket.cache.path parameter is ignored because ClickHouse was built without support of krb5 " + "library."); #endif // USE_KRB5 } @@ -125,7 +131,7 @@ HDFSBuilderWrapper createHDFSBuilder(const String & uri_str, const Poco::Util::A hdfsBuilderConfSetStr(builder.get(), "input.write.timeout", "60000"); // 1 min hdfsBuilderConfSetStr(builder.get(), "input.connect.timeout", "60000"); // 1 min - String user_info = uri.getUserInfo(); + const String & user_info = uri.getUserInfo(); String user; if (!user_info.empty() && user_info.front() != ':') { diff --git a/src/Storages/ObjectStorage/ReadBufferIterator.cpp b/src/Storages/ObjectStorage/ReadBufferIterator.cpp index f0f3de97652..d1ef90518e7 100644 --- a/src/Storages/ObjectStorage/ReadBufferIterator.cpp +++ b/src/Storages/ObjectStorage/ReadBufferIterator.cpp @@ -142,8 +142,7 @@ String ReadBufferIterator::getLastFilePath() const { if (current_object_info) return current_object_info->getPath(); - else - return ""; + return ""; } std::unique_ptr ReadBufferIterator::recreateLastReadBuffer() diff --git a/src/Storages/ObjectStorage/StorageObjectStorage.cpp b/src/Storages/ObjectStorage/StorageObjectStorage.cpp index 040ce8db51d..7714fb6e86b 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorage.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorage.cpp @@ -455,30 +455,25 @@ SchemaCache & StorageObjectStorage::getSchemaCache(const ContextPtr & context, c DEFAULT_SCHEMA_CACHE_ELEMENTS)); return schema_cache; } - else if (storage_type_name == "hdfs") + if (storage_type_name == "hdfs") { static SchemaCache schema_cache( - context->getConfigRef().getUInt( - "schema_inference_cache_max_elements_for_hdfs", - DEFAULT_SCHEMA_CACHE_ELEMENTS)); + context->getConfigRef().getUInt("schema_inference_cache_max_elements_for_hdfs", DEFAULT_SCHEMA_CACHE_ELEMENTS)); return schema_cache; } - else if (storage_type_name == "azure") + if (storage_type_name == "azure") { static SchemaCache schema_cache( - context->getConfigRef().getUInt( - "schema_inference_cache_max_elements_for_azure", - DEFAULT_SCHEMA_CACHE_ELEMENTS)); + context->getConfigRef().getUInt("schema_inference_cache_max_elements_for_azure", DEFAULT_SCHEMA_CACHE_ELEMENTS)); return schema_cache; } - else if (storage_type_name == "local") + if (storage_type_name == "local") { static SchemaCache schema_cache( context->getConfigRef().getUInt("schema_inference_cache_max_elements_for_local", DEFAULT_SCHEMA_CACHE_ELEMENTS)); return schema_cache; } - else - throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Unsupported storage type: {}", storage_type_name); + throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Unsupported storage type: {}", storage_type_name); } void StorageObjectStorage::Configuration::initialize( @@ -529,8 +524,7 @@ bool StorageObjectStorage::Configuration::withGlobsIgnorePartitionWildcard() con { if (!withPartitionWildcard()) return withGlobs(); - else - return PartitionedSink::replaceWildcards(getPath(), "").find_first_of("*?{") != std::string::npos; + return PartitionedSink::replaceWildcards(getPath(), "").find_first_of("*?{") != std::string::npos; } bool StorageObjectStorage::Configuration::isPathWithGlobs() const diff --git a/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp b/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp index 0bb6660191f..176f20cf5ca 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageCluster.cpp @@ -123,8 +123,7 @@ RemoteQueryExecutor::Extension StorageObjectStorageCluster::getTaskIteratorExten auto object_info = iterator->next(0); if (object_info) return object_info->getPath(); - else - return ""; + return ""; }); return RemoteQueryExecutor::Extension{ .task_iterator = std::move(callback) }; } diff --git a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp index 440a4af4b64..baf6970517d 100644 --- a/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp +++ b/src/Storages/ObjectStorage/StorageObjectStorageSource.cpp @@ -100,8 +100,7 @@ std::string StorageObjectStorageSource::getUniqueStoragePathIdentifier( if (include_connection_info) return fs::path(configuration.getDataSourceDescription()) / path; - else - return fs::path(configuration.getNamespace()) / path; + return fs::path(configuration.getNamespace()) / path; } std::shared_ptr StorageObjectStorageSource::createFileIterator( @@ -503,7 +502,7 @@ StorageObjectStorageSource::GlobIterator::GlobIterator( { throw Exception(ErrorCodes::BAD_ARGUMENTS, "Expression can not have wildcards inside namespace name"); } - else if (configuration->isPathWithGlobs()) + if (configuration->isPathWithGlobs()) { const auto key_with_globs = configuration_->getPath(); const auto key_prefix = configuration->getPathWithoutGlobs(); @@ -512,9 +511,7 @@ StorageObjectStorageSource::GlobIterator::GlobIterator( matcher = std::make_unique(makeRegexpPatternFromGlobs(key_with_globs)); if (!matcher->ok()) { - throw Exception( - ErrorCodes::CANNOT_COMPILE_REGEXP, - "Cannot compile regex from glob ({}): {}", key_with_globs, matcher->error()); + throw Exception(ErrorCodes::CANNOT_COMPILE_REGEXP, "Cannot compile regex from glob ({}): {}", key_with_globs, matcher->error()); } recursive = key_with_globs == "/**"; @@ -526,9 +523,10 @@ StorageObjectStorageSource::GlobIterator::GlobIterator( } else { - throw Exception(ErrorCodes::BAD_ARGUMENTS, - "Using glob iterator with path without globs is not allowed (used path: {})", - configuration->getPath()); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Using glob iterator with path without globs is not allowed (used path: {})", + configuration->getPath()); } } @@ -824,8 +822,7 @@ StorageObjectStorageSource::ArchiveIterator::nextImpl(size_t processor) path_in_archive = file_enumerator->getFileName(); if (!filter(path_in_archive)) continue; - else - current_file_info = file_enumerator->getFileInfo(); + current_file_info = file_enumerator->getFileInfo(); } else { @@ -839,8 +836,7 @@ StorageObjectStorageSource::ArchiveIterator::nextImpl(size_t processor) archive_reader = createArchiveReader(archive_object); if (!archive_reader->fileExists(path_in_archive)) continue; - else - current_file_info = archive_reader->getFileInfo(path_in_archive); + current_file_info = archive_reader->getFileInfo(path_in_archive); } break; } diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp index cba3e8bfa7c..7d9e22f67a0 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp @@ -89,8 +89,7 @@ public: { if (if_exists) return false; - else - throw Exception(ErrorCodes::BAD_ARGUMENTS, "File status for {} doesn't exist", filename); + throw Exception(ErrorCodes::BAD_ARGUMENTS, "File status for {} doesn't exist", filename); } file_statuses.erase(it); return true; @@ -290,7 +289,7 @@ ObjectStorageQueueTableMetadata ObjectStorageQueueMetadata::syncWithKeeper( code, exception.getPathForFirstFailedOp(), zookeeper_path.string()); continue; } - else if (code != Coordination::Error::ZOK) + if (code != Coordination::Error::ZOK) zkutil::KeeperMultiException::check(code, requests, responses); return table_metadata; diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueOrderedFileMetadata.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueOrderedFileMetadata.cpp index 3b711a892c9..75a96328051 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueOrderedFileMetadata.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueOrderedFileMetadata.cpp @@ -30,8 +30,7 @@ namespace { if (buckets_num > 1) return getProcessedPathForBucket(zk_path, getBucketForPathImpl(path, buckets_num)); - else - return zk_path / "processed"; + return zk_path / "processed"; } zkutil::ZooKeeperPtr getZooKeeper() @@ -135,8 +134,7 @@ std::vector ObjectStorageQueueOrderedFileMetadata::getMetadataPaths paths.push_back("buckets/" + toString(i)); return paths; } - else - return {"failed", "processing"}; + return {"failed", "processing"}; } bool ObjectStorageQueueOrderedFileMetadata::getMaxProcessedFile( diff --git a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSource.cpp b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSource.cpp index 462953aaf27..5e143c1df1c 100644 --- a/src/Storages/ObjectStorageQueue/ObjectStorageQueueSource.cpp +++ b/src/Storages/ObjectStorageQueue/ObjectStorageQueueSource.cpp @@ -321,43 +321,35 @@ ObjectStorageQueueSource::FileIterator::getNextKeyFromAcquiredBucket(size_t proc /// Bucket is already acquired, process the file. return std::pair{object_info, current_bucket_holder->getBucketInfo()}; } - else + + auto acquired_bucket = metadata->tryAcquireBucket(bucket, current_processor); + if (acquired_bucket) { - auto acquired_bucket = metadata->tryAcquireBucket(bucket, current_processor); - if (acquired_bucket) - { - bucket_holder_it->second.push_back(acquired_bucket); - current_bucket_holder = bucket_holder_it->second.back().get(); + bucket_holder_it->second.push_back(acquired_bucket); + current_bucket_holder = bucket_holder_it->second.back().get(); - bucket_cache.processor = current_processor; - if (!bucket_cache.keys.empty()) - { - /// We have to maintain ordering between keys, - /// so if some keys are already in cache - start with them. - bucket_cache.keys.emplace_back(object_info); - object_info = bucket_cache.keys.front(); - bucket_cache.keys.pop_front(); - } - return std::pair{object_info, current_bucket_holder->getBucketInfo()}; - } - else + bucket_cache.processor = current_processor; + if (!bucket_cache.keys.empty()) { - LOG_TEST(log, "Bucket {} is already locked for processing", bucket); + /// We have to maintain ordering between keys, + /// so if some keys are already in cache - start with them. bucket_cache.keys.emplace_back(object_info); - continue; + object_info = bucket_cache.keys.front(); + bucket_cache.keys.pop_front(); } + return std::pair{object_info, current_bucket_holder->getBucketInfo()}; } - } - else - { - LOG_TEST(log, "Reached the end of file iterator"); - iterator_finished = true; - if (listed_keys_cache.empty()) - return {}; - else - continue; + LOG_TEST(log, "Bucket {} is already locked for processing", bucket); + bucket_cache.keys.emplace_back(object_info); + continue; } + + LOG_TEST(log, "Reached the end of file iterator"); + iterator_finished = true; + + if (listed_keys_cache.empty()) + return {}; } } @@ -590,20 +582,27 @@ Chunk ObjectStorageQueueSource::generateImpl() total_processed_rows, total_processed_bytes, processed_files.size()); break; } - else if (queue_settings.max_processed_bytes_before_commit - && total_processed_bytes == queue_settings.max_processed_bytes_before_commit) + if (queue_settings.max_processed_bytes_before_commit && total_processed_bytes == queue_settings.max_processed_bytes_before_commit) { - LOG_TRACE(log, "Number of max processed bytes before commit reached " - "(rows: {}, bytes: {}, files: {})", - total_processed_rows, total_processed_bytes, processed_files.size()); + LOG_TRACE( + log, + "Number of max processed bytes before commit reached " + "(rows: {}, bytes: {}, files: {})", + total_processed_rows, + total_processed_bytes, + processed_files.size()); break; } - else if (queue_settings.max_processing_time_sec_before_commit - && total_stopwatch.elapsedSeconds() >= queue_settings.max_processing_time_sec_before_commit) + if (queue_settings.max_processing_time_sec_before_commit + && total_stopwatch.elapsedSeconds() >= queue_settings.max_processing_time_sec_before_commit) { - LOG_TRACE(log, "Max processing time before commit reached " - "(rows: {}, bytes: {}, files: {})", - total_processed_rows, total_processed_bytes, processed_files.size()); + LOG_TRACE( + log, + "Max processing time before commit reached " + "(rows: {}, bytes: {}, files: {})", + total_processed_rows, + total_processed_bytes, + processed_files.size()); break; } } diff --git a/src/Storages/PartitionCommands.cpp b/src/Storages/PartitionCommands.cpp index fd5964c7034..0f7dadd75b6 100644 --- a/src/Storages/PartitionCommands.cpp +++ b/src/Storages/PartitionCommands.cpp @@ -28,7 +28,7 @@ std::optional PartitionCommand::parse(const ASTAlterCommand * res.part = command_ast->part; return res; } - else if (command_ast->type == ASTAlterCommand::DROP_DETACHED_PARTITION) + if (command_ast->type == ASTAlterCommand::DROP_DETACHED_PARTITION) { PartitionCommand res; res.type = DROP_DETACHED_PARTITION; @@ -36,14 +36,14 @@ std::optional PartitionCommand::parse(const ASTAlterCommand * res.part = command_ast->part; return res; } - else if (command_ast->type == ASTAlterCommand::FORGET_PARTITION) + if (command_ast->type == ASTAlterCommand::FORGET_PARTITION) { PartitionCommand res; res.type = FORGET_PARTITION; res.partition = command_ast->partition->clone(); return res; } - else if (command_ast->type == ASTAlterCommand::ATTACH_PARTITION) + if (command_ast->type == ASTAlterCommand::ATTACH_PARTITION) { PartitionCommand res; res.type = ATTACH_PARTITION; @@ -51,7 +51,7 @@ std::optional PartitionCommand::parse(const ASTAlterCommand * res.part = command_ast->part; return res; } - else if (command_ast->type == ASTAlterCommand::MOVE_PARTITION) + if (command_ast->type == ASTAlterCommand::MOVE_PARTITION) { PartitionCommand res; res.type = MOVE_PARTITION; @@ -80,7 +80,7 @@ std::optional PartitionCommand::parse(const ASTAlterCommand * res.move_destination_name = command_ast->move_destination_name; return res; } - else if (command_ast->type == ASTAlterCommand::REPLACE_PARTITION) + if (command_ast->type == ASTAlterCommand::REPLACE_PARTITION) { PartitionCommand res; res.type = REPLACE_PARTITION; @@ -90,7 +90,7 @@ std::optional PartitionCommand::parse(const ASTAlterCommand * res.from_table = command_ast->from_table; return res; } - else if (command_ast->type == ASTAlterCommand::FETCH_PARTITION) + if (command_ast->type == ASTAlterCommand::FETCH_PARTITION) { PartitionCommand res; res.type = FETCH_PARTITION; @@ -99,7 +99,7 @@ std::optional PartitionCommand::parse(const ASTAlterCommand * res.part = command_ast->part; return res; } - else if (command_ast->type == ASTAlterCommand::FREEZE_PARTITION) + if (command_ast->type == ASTAlterCommand::FREEZE_PARTITION) { PartitionCommand res; res.type = FREEZE_PARTITION; @@ -107,14 +107,14 @@ std::optional PartitionCommand::parse(const ASTAlterCommand * res.with_name = command_ast->with_name; return res; } - else if (command_ast->type == ASTAlterCommand::FREEZE_ALL) + if (command_ast->type == ASTAlterCommand::FREEZE_ALL) { PartitionCommand res; res.type = PartitionCommand::FREEZE_ALL_PARTITIONS; res.with_name = command_ast->with_name; return res; } - else if (command_ast->type == ASTAlterCommand::UNFREEZE_PARTITION) + if (command_ast->type == ASTAlterCommand::UNFREEZE_PARTITION) { PartitionCommand res; res.type = PartitionCommand::UNFREEZE_PARTITION; @@ -122,15 +122,14 @@ std::optional PartitionCommand::parse(const ASTAlterCommand * res.with_name = command_ast->with_name; return res; } - else if (command_ast->type == ASTAlterCommand::UNFREEZE_ALL) + if (command_ast->type == ASTAlterCommand::UNFREEZE_ALL) { PartitionCommand res; res.type = PartitionCommand::UNFREEZE_ALL_PARTITIONS; res.with_name = command_ast->with_name; return res; } - else - return {}; + return {}; } std::string PartitionCommand::typeToString() const diff --git a/src/Storages/RabbitMQ/RabbitMQSource.cpp b/src/Storages/RabbitMQ/RabbitMQSource.cpp index 8f3f9daf088..a7b652d76dd 100644 --- a/src/Storages/RabbitMQ/RabbitMQSource.cpp +++ b/src/Storages/RabbitMQ/RabbitMQSource.cpp @@ -184,10 +184,8 @@ Chunk RabbitMQSource::generateImpl() return 1; } - else - { - throw std::move(e); - } + + throw std::move(e); }; StreamingFormatExecutor executor(non_virtual_header, input_format, on_error); @@ -274,7 +272,7 @@ Chunk RabbitMQSource::generateImpl() { break; } - else if (new_rows == 0) + if (new_rows == 0) { if (remaining_execution_time) consumer->waitForMessages(remaining_execution_time); diff --git a/src/Storages/RabbitMQ/StorageRabbitMQ.cpp b/src/Storages/RabbitMQ/StorageRabbitMQ.cpp index 950cce9861c..ce667847cdb 100644 --- a/src/Storages/RabbitMQ/StorageRabbitMQ.cpp +++ b/src/Storages/RabbitMQ/StorageRabbitMQ.cpp @@ -271,8 +271,7 @@ String StorageRabbitMQ::getTableBasedName(String name, const StorageID & table_i { if (name.empty()) return fmt::format("{}_{}", table_id.database_name, table_id.table_name); - else - return fmt::format("{}_{}_{}", name, table_id.database_name, table_id.table_name); + return fmt::format("{}_{}_{}", name, table_id.database_name, table_id.table_name); } @@ -1258,11 +1257,10 @@ bool StorageRabbitMQ::tryStreamToViews() LOG_TRACE(log, "Reschedule streaming. Queues are empty."); return false; } - else - { - LOG_TEST(log, "Will start background loop to let messages be pushed to channel"); - startLoop(); - } + + LOG_TEST(log, "Will start background loop to let messages be pushed to channel"); + startLoop(); + /// Reschedule. return true; diff --git a/src/Storages/RedisCommon.cpp b/src/Storages/RedisCommon.cpp index a0534a9e23b..5523e05850b 100644 --- a/src/Storages/RedisCommon.cpp +++ b/src/Storages/RedisCommon.cpp @@ -55,7 +55,7 @@ RedisStorageType parseStorageType(const String & storage_type_str) { if (storage_type_str == "hash_map") return RedisStorageType::HASH_MAP; - else if (!storage_type_str.empty() && storage_type_str != "simple") + if (!storage_type_str.empty() && storage_type_str != "simple") throw Exception(ErrorCodes::INVALID_REDIS_STORAGE_TYPE, "Unknown storage type {} for Redis dictionary", storage_type_str); return RedisStorageType::SIMPLE; diff --git a/src/Storages/SelectQueryDescription.cpp b/src/Storages/SelectQueryDescription.cpp index 7129c8c66f0..6ec4f86a2a1 100644 --- a/src/Storages/SelectQueryDescription.cpp +++ b/src/Storages/SelectQueryDescription.cpp @@ -56,13 +56,14 @@ StorageID extractDependentTableFromSelectQuery(ASTSelectQuery & query, ContextPt { return StorageID(db_and_table->database, db_and_table->table/*, db_and_table->uuid*/); } - else if (auto subquery = extractTableExpression(query, 0)) + if (auto subquery = extractTableExpression(query, 0)) { auto * ast_select = subquery->as(); if (!ast_select) - throw Exception(ErrorCodes::QUERY_IS_NOT_SUPPORTED_IN_MATERIALIZED_VIEW, - "StorageMaterializedView cannot be created from table functions ({})", - serializeAST(*subquery)); + throw Exception( + ErrorCodes::QUERY_IS_NOT_SUPPORTED_IN_MATERIALIZED_VIEW, + "StorageMaterializedView cannot be created from table functions ({})", + serializeAST(*subquery)); if (ast_select->list_of_selects->children.size() != 1) throw Exception(ErrorCodes::QUERY_IS_NOT_SUPPORTED_IN_MATERIALIZED_VIEW, "UNION is not supported for MATERIALIZED VIEW"); @@ -70,8 +71,7 @@ StorageID extractDependentTableFromSelectQuery(ASTSelectQuery & query, ContextPt return extractDependentTableFromSelectQuery(inner_query->as(), context, false); } - else - return StorageID::createEmpty(); + return StorageID::createEmpty(); } @@ -106,6 +106,7 @@ static bool isSingleSelect(const ASTPtr & select, ASTPtr & res) if (new_select->list_of_selects->children.size() != 1) return false; + auto & new_inner_query = new_select->list_of_selects->children.at(0); if (new_inner_query->as()) { diff --git a/src/Storages/Statistics/ConditionSelectivityEstimator.cpp b/src/Storages/Statistics/ConditionSelectivityEstimator.cpp index 2b4d3f3e8b7..0f107083138 100644 --- a/src/Storages/Statistics/ConditionSelectivityEstimator.cpp +++ b/src/Storages/Statistics/ConditionSelectivityEstimator.cpp @@ -69,9 +69,9 @@ static std::pair tryToExtractSingleColumn(const RPNBuilderTreeNod auto subresult = tryToExtractSingleColumn(function_argument); if (subresult.second == 0) /// the subnode contains 0 column continue; - else if (subresult.second > 1) /// the subnode contains more than 1 column + if (subresult.second > 1) /// the subnode contains more than 1 column return subresult; - else if (result.second == 0 || result.first == subresult.first) /// subnodes contain same column. + if (result.second == 0 || result.first == subresult.first) /// subnodes contain same column. result = subresult; else return {"", 2}; @@ -103,20 +103,18 @@ Float64 ConditionSelectivityEstimator::estimateRowCount(const RPNBuilderTreeNode { if (op == "equals") return default_cond_equal_factor * total_rows; - else if (op == "less" || op == "lessOrEquals" || op == "greater" || op == "greaterOrEquals") + if (op == "less" || op == "lessOrEquals" || op == "greater" || op == "greaterOrEquals") return default_cond_range_factor * total_rows; - else - return default_unknown_cond_factor * total_rows; + return default_unknown_cond_factor * total_rows; } if (op == "equals") return estimator.estimateEqual(val, total_rows); - else if (op == "less" || op == "lessOrEquals") + if (op == "less" || op == "lessOrEquals") return estimator.estimateLess(val, total_rows); - else if (op == "greater" || op == "greaterOrEquals") + if (op == "greater" || op == "greaterOrEquals") return estimator.estimateGreater(val, total_rows); - else - return default_unknown_cond_factor * total_rows; + return default_unknown_cond_factor * total_rows; } void ConditionSelectivityEstimator::incrementRowCount(UInt64 rows) diff --git a/src/Storages/StatisticsDescription.cpp b/src/Storages/StatisticsDescription.cpp index ac7fa8898de..8c9046cb618 100644 --- a/src/Storages/StatisticsDescription.cpp +++ b/src/Storages/StatisticsDescription.cpp @@ -108,7 +108,7 @@ void ColumnStatisticsDescription::merge(const ColumnStatisticsDescription & othe { throw Exception(ErrorCodes::ILLEGAL_STATISTICS, "Statistics type name {} has existed in column {}", stats_type, merging_column_name); } - else if (!types_to_desc.contains(stats_type)) + if (!types_to_desc.contains(stats_type)) types_to_desc.emplace(stats_type, stats_desc); } } diff --git a/src/Storages/StorageBuffer.cpp b/src/Storages/StorageBuffer.cpp index fc1126680e9..f56a5dbf704 100644 --- a/src/Storages/StorageBuffer.cpp +++ b/src/Storages/StorageBuffer.cpp @@ -1033,7 +1033,7 @@ void StorageBuffer::writeBlockToDestination(const Block & block, StoragePtr tabl Block block_to_write; for (size_t i : collections::range(0, structure_of_destination_table.columns())) { - auto dst_col = structure_of_destination_table.getByPosition(i); + const auto & dst_col = structure_of_destination_table.getByPosition(i); if (block.has(dst_col.name)) { auto column = block.getByName(dst_col.name); diff --git a/src/Storages/StorageDictionary.cpp b/src/Storages/StorageDictionary.cpp index 4a290ca3a94..e9f732466ff 100644 --- a/src/Storages/StorageDictionary.cpp +++ b/src/Storages/StorageDictionary.cpp @@ -343,26 +343,25 @@ void registerStorageDictionary(StorageFactory & factory) return result_storage; } - else + + /// Create dictionary storage that is view of underlying dictionary + + if (args.engine_args.size() != 1) + throw Exception( + ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "Storage Dictionary requires single parameter: name of dictionary"); + + args.engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(args.engine_args[0], local_context); + String dictionary_name = checkAndGetLiteralArgument(args.engine_args[0], "dictionary_name"); + + if (args.mode <= LoadingStrictnessLevel::CREATE) { - /// Create dictionary storage that is view of underlying dictionary - - if (args.engine_args.size() != 1) - throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "Storage Dictionary requires single parameter: name of dictionary"); - - args.engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(args.engine_args[0], local_context); - String dictionary_name = checkAndGetLiteralArgument(args.engine_args[0], "dictionary_name"); - - if (args.mode <= LoadingStrictnessLevel::CREATE) - { - const auto & dictionary = args.getContext()->getExternalDictionariesLoader().getDictionary(dictionary_name, args.getContext()); - const DictionaryStructure & dictionary_structure = dictionary->getStructure(); - checkNamesAndTypesCompatibleWithDictionary(dictionary_name, args.columns, dictionary_structure); - } - - return std::make_shared( - args.table_id, dictionary_name, args.columns, args.comment, StorageDictionary::Location::Custom, local_context); + const auto & dictionary = args.getContext()->getExternalDictionariesLoader().getDictionary(dictionary_name, args.getContext()); + const DictionaryStructure & dictionary_structure = dictionary->getStructure(); + checkNamesAndTypesCompatibleWithDictionary(dictionary_name, args.columns, dictionary_structure); } + + return std::make_shared( + args.table_id, dictionary_name, args.columns, args.comment, StorageDictionary::Location::Custom, local_context); }); } diff --git a/src/Storages/StorageDistributed.cpp b/src/Storages/StorageDistributed.cpp index 2d09e4fe53f..b26abda21f9 100644 --- a/src/Storages/StorageDistributed.cpp +++ b/src/Storages/StorageDistributed.cpp @@ -272,7 +272,7 @@ public: std::string name = node->getColumnName(); if (block_with_constants.has(name)) { - auto result = block_with_constants.getByName(name); + const auto & result = block_with_constants.getByName(name); if (!isColumnConst(*result.column)) return; @@ -452,17 +452,15 @@ QueryProcessingStage::Enum StorageDistributed::getQueryProcessingStage( { if (settings[Setting::distributed_push_down_limit]) return QueryProcessingStage::WithMergeableStateAfterAggregationAndLimit; - else - return QueryProcessingStage::WithMergeableStateAfterAggregation; - } - else - { - /// NOTE: distributed_group_by_no_merge=1 does not respect distributed_push_down_limit - /// (since in this case queries processed separately and the initiator is just a proxy in this case). - if (to_stage != QueryProcessingStage::Complete) - throw Exception(ErrorCodes::LOGICAL_ERROR, "Queries with distributed_group_by_no_merge=1 should be processed to Complete stage"); - return QueryProcessingStage::Complete; + return QueryProcessingStage::WithMergeableStateAfterAggregation; } + + /// NOTE: distributed_group_by_no_merge=1 does not respect distributed_push_down_limit + /// (since in this case queries processed separately and the initiator is just a proxy in this case). + if (to_stage != QueryProcessingStage::Complete) + throw Exception( + ErrorCodes::LOGICAL_ERROR, "Queries with distributed_group_by_no_merge=1 should be processed to Complete stage"); + return QueryProcessingStage::Complete; } /// Nested distributed query cannot return Complete stage, @@ -481,7 +479,7 @@ QueryProcessingStage::Enum StorageDistributed::getQueryProcessingStage( /// relevant for Distributed over Distributed return std::max(to_stage, QueryProcessingStage::Complete); } - else if (nodes == 0) + if (nodes == 0) { /// In case of 0 shards, the query should be processed fully on the initiator, /// since we need to apply aggregations. @@ -1528,10 +1526,9 @@ ClusterPtr StorageDistributed::getOptimizedCluster( { if (!has_sharding_key) throw Exception(ErrorCodes::UNABLE_TO_SKIP_UNUSED_SHARDS, "No sharding key"); - else if (!sharding_key_is_usable) + if (!sharding_key_is_usable) throw Exception(ErrorCodes::UNABLE_TO_SKIP_UNUSED_SHARDS, "Sharding key is not deterministic"); - else - throw Exception(ErrorCodes::UNABLE_TO_SKIP_UNUSED_SHARDS, "Sharding key {} is not used", sharding_key_column_name); + throw Exception(ErrorCodes::UNABLE_TO_SKIP_UNUSED_SHARDS, "Sharding key {} is not used", sharding_key_column_name); } return {}; @@ -1542,6 +1539,7 @@ IColumn::Selector StorageDistributed::createSelector(const ClusterPtr cluster, c const auto & slot_to_shard = cluster->getSlotToShard(); const IColumn * column = result.column.get(); +/// NOLINTBEGIN(readability-else-after-return) // If result.type is DataTypeLowCardinality, do shard according to its dictionaryType #define CREATE_FOR_TYPE(TYPE) \ if (typeid_cast(result.type.get())) \ @@ -1563,6 +1561,7 @@ IColumn::Selector StorageDistributed::createSelector(const ClusterPtr cluster, c throw Exception(ErrorCodes::TYPE_MISMATCH, "Sharding key expression does not evaluate to an integer type"); } +/// NOLINTEND(readability-else-after-return) ClusterPtr StorageDistributed::skipUnusedShardsWithAnalyzer( ClusterPtr cluster, diff --git a/src/Storages/StorageExecutable.h b/src/Storages/StorageExecutable.h index 6748bb3223e..90a7d0f950d 100644 --- a/src/Storages/StorageExecutable.h +++ b/src/Storages/StorageExecutable.h @@ -29,8 +29,7 @@ public: { if (settings.is_executable_pool) return "ExecutablePool"; - else - return "Executable"; + return "Executable"; } void read( diff --git a/src/Storages/StorageFactory.cpp b/src/Storages/StorageFactory.cpp index a3579df6c6a..10746a6666c 100644 --- a/src/Storages/StorageFactory.cpp +++ b/src/Storages/StorageFactory.cpp @@ -132,23 +132,26 @@ StoragePtr StorageFactory::get( { throw Exception(ErrorCodes::INCORRECT_QUERY, "Direct creation of tables with ENGINE View is not supported, use CREATE VIEW statement"); } - else if (name == "MaterializedView") + if (name == "MaterializedView") { - throw Exception(ErrorCodes::INCORRECT_QUERY, - "Direct creation of tables with ENGINE MaterializedView " - "is not supported, use CREATE MATERIALIZED VIEW statement"); + throw Exception( + ErrorCodes::INCORRECT_QUERY, + "Direct creation of tables with ENGINE MaterializedView " + "is not supported, use CREATE MATERIALIZED VIEW statement"); } - else if (name == "LiveView") + if (name == "LiveView") { - throw Exception(ErrorCodes::INCORRECT_QUERY, - "Direct creation of tables with ENGINE LiveView " - "is not supported, use CREATE LIVE VIEW statement"); + throw Exception( + ErrorCodes::INCORRECT_QUERY, + "Direct creation of tables with ENGINE LiveView " + "is not supported, use CREATE LIVE VIEW statement"); } - else if (name == "WindowView") + if (name == "WindowView") { - throw Exception(ErrorCodes::INCORRECT_QUERY, - "Direct creation of tables with ENGINE WindowView " - "is not supported, use CREATE WINDOW VIEW statement"); + throw Exception( + ErrorCodes::INCORRECT_QUERY, + "Direct creation of tables with ENGINE WindowView " + "is not supported, use CREATE WINDOW VIEW statement"); } auto it = storages.find(name); @@ -157,8 +160,7 @@ StoragePtr StorageFactory::get( auto hints = getHints(name); if (!hints.empty()) throw Exception(ErrorCodes::UNKNOWN_STORAGE, "Unknown table engine {}. Maybe you meant: {}", name, toString(hints)); - else - throw Exception(ErrorCodes::UNKNOWN_STORAGE, "Unknown table engine {}", name); + throw Exception(ErrorCodes::UNKNOWN_STORAGE, "Unknown table engine {}", name); } auto check_feature = [&](String feature_description, FeatureMatcherFn feature_matcher_fn) diff --git a/src/Storages/StorageFile.cpp b/src/Storages/StorageFile.cpp index 46f4800b497..7485a19e67f 100644 --- a/src/Storages/StorageFile.cpp +++ b/src/Storages/StorageFile.cpp @@ -1173,16 +1173,14 @@ String StorageFileSource::FilesIterator::next() { if (distributed_processing) return getContext()->getReadTaskCallback()(); - else - { - const auto & fs = isReadFromArchive() ? archive_info->paths_to_archives : files; - auto current_index = index.fetch_add(1, std::memory_order_relaxed); - if (current_index >= fs.size()) - return {}; + const auto & fs = isReadFromArchive() ? archive_info->paths_to_archives : files; - return fs[current_index]; - } + auto current_index = index.fetch_add(1, std::memory_order_relaxed); + if (current_index >= fs.size()) + return {}; + + return fs[current_index]; } const String & StorageFileSource::FilesIterator::getFileNameInArchive() @@ -2001,62 +1999,60 @@ SinkToStoragePtr StorageFile::write( context, flags); } - else + + String path; + if (!paths.empty()) { - String path; - if (!paths.empty()) + if (is_path_with_globs) + throw Exception(ErrorCodes::DATABASE_ACCESS_DENIED, + "Table '{}' is in readonly mode because of globs in filepath", + getStorageID().getNameForLogs()); + + path = paths.front(); + fs::create_directories(fs::path(path).parent_path()); + + std::error_code error_code; + if (!context->getSettingsRef()[Setting::engine_file_truncate_on_insert] && !is_path_with_globs + && !FormatFactory::instance().checkIfFormatSupportAppend(format_name, context, format_settings) + && fs::file_size(path, error_code) != 0 && !error_code) { - if (is_path_with_globs) - throw Exception(ErrorCodes::DATABASE_ACCESS_DENIED, - "Table '{}' is in readonly mode because of globs in filepath", - getStorageID().getNameForLogs()); - - path = paths.front(); - fs::create_directories(fs::path(path).parent_path()); - - std::error_code error_code; - if (!context->getSettingsRef()[Setting::engine_file_truncate_on_insert] && !is_path_with_globs - && !FormatFactory::instance().checkIfFormatSupportAppend(format_name, context, format_settings) - && fs::file_size(path, error_code) != 0 && !error_code) + if (context->getSettingsRef()[Setting::engine_file_allow_create_multiple_files]) { - if (context->getSettingsRef()[Setting::engine_file_allow_create_multiple_files]) + auto pos = path.find_first_of('.', path.find_last_of('/')); + size_t index = paths.size(); + String new_path; + do { - auto pos = path.find_first_of('.', path.find_last_of('/')); - size_t index = paths.size(); - String new_path; - do - { - new_path = path.substr(0, pos) + "." + std::to_string(index) + (pos == std::string::npos ? "" : path.substr(pos)); - ++index; - } - while (fs::exists(new_path)); - paths.push_back(new_path); - path = new_path; + new_path = path.substr(0, pos) + "." + std::to_string(index) + (pos == std::string::npos ? "" : path.substr(pos)); + ++index; } - else - throw Exception( - ErrorCodes::CANNOT_APPEND_TO_FILE, - "Cannot append data in format {} to file, because this format doesn't support appends." - " You can allow to create a new file " - "on each insert by enabling setting engine_file_allow_create_multiple_files", - format_name); + while (fs::exists(new_path)); + paths.push_back(new_path); + path = new_path; } + else + throw Exception( + ErrorCodes::CANNOT_APPEND_TO_FILE, + "Cannot append data in format {} to file, because this format doesn't support appends." + " You can allow to create a new file " + "on each insert by enabling setting engine_file_allow_create_multiple_files", + format_name); } - - return std::make_shared( - metadata_snapshot, - getStorageID().getNameForLogs(), - std::unique_lock{rwlock, getLockTimeout(context)}, - table_fd, - use_table_fd, - base_path, - path, - chooseCompressionMethod(path, compression_method), - format_settings, - format_name, - context, - flags); } + + return std::make_shared( + metadata_snapshot, + getStorageID().getNameForLogs(), + std::unique_lock{rwlock, getLockTimeout(context)}, + table_fd, + use_table_fd, + base_path, + path, + chooseCompressionMethod(path, compression_method), + format_settings, + format_name, + context, + flags); } bool StorageFile::storesDataOnDisk() const @@ -2218,8 +2214,9 @@ void registerStorageFile(StorageFactory & factory) if (0 <= source_fd) /// File descriptor return std::make_shared(source_fd, storage_args); - else /// User's file - return std::make_shared(source_path, factory_args.getContext()->getUserFilesPath(), false, storage_args); + + /// User's file + return std::make_shared(source_path, factory_args.getContext()->getUserFilesPath(), false, storage_args); }, storage_features); } diff --git a/src/Storages/StorageFuzzJSON.cpp b/src/Storages/StorageFuzzJSON.cpp index fc73f246d35..4eb8ca88223 100644 --- a/src/Storages/StorageFuzzJSON.cpp +++ b/src/Storages/StorageFuzzJSON.cpp @@ -63,20 +63,19 @@ JSONValue::Type JSONValue::getType(const JSONValue & v) assert(!v.object); return JSONValue::Type::Fixed; } - else if (v.array) + if (v.array) { assert(!v.fixed); assert(!v.object); return JSONValue::Type::Array; } - else if (v.object) + if (v.object) { assert(!v.fixed); assert(!v.array); return JSONValue::Type::Object; } - else - throw Exception(ErrorCodes::LOGICAL_ERROR, "Failed to determine JSON node type."); + throw Exception(ErrorCodes::LOGICAL_ERROR, "Failed to determine JSON node type."); } // A node represents either a JSON field (a key-value pair) or a JSON value. diff --git a/src/Storages/StorageKeeperMap.cpp b/src/Storages/StorageKeeperMap.cpp index 2b88039f1fa..316eced1ed6 100644 --- a/src/Storages/StorageKeeperMap.cpp +++ b/src/Storages/StorageKeeperMap.cpp @@ -584,7 +584,7 @@ StorageKeeperMap::StorageKeeperMap( log, "It looks like a table on path {} was created by another server at the same moment, will retry", zk_root_path); return; } - else if (code != Coordination::Error::ZOK) + if (code != Coordination::Error::ZOK) { zkutil::KeeperMultiException::check(code, create_requests, create_responses); } @@ -792,12 +792,12 @@ void StorageKeeperMap::drop() LOG_INFO(log, "Metadata is being removed by another table"); return; } - else if (code == Coordination::Error::ZNOTEMPTY) + if (code == Coordination::Error::ZNOTEMPTY) { LOG_WARNING(log, "Another table is using the same path, metadata will not be deleted"); return; } - else if (code != Coordination::Error::ZOK) + if (code != Coordination::Error::ZOK) zkutil::KeeperMultiException::check(code, ops, responses); auto metadata_drop_lock = zkutil::EphemeralNodeHolder::existing(zk_dropped_lock_path, *client); diff --git a/src/Storages/StorageMaterializedView.cpp b/src/Storages/StorageMaterializedView.cpp index c2c66fabb57..117e3e8e7de 100644 --- a/src/Storages/StorageMaterializedView.cpp +++ b/src/Storages/StorageMaterializedView.cpp @@ -646,11 +646,11 @@ void StorageMaterializedView::checkAlterIsPossible(const AlterCommands & command continue; } - else if (command.isCommentAlter()) + if (command.isCommentAlter()) continue; - else if (command.type == AlterCommand::MODIFY_QUERY) + if (command.type == AlterCommand::MODIFY_QUERY) continue; - else if (command.type == AlterCommand::MODIFY_REFRESH && refresher) + if (command.type == AlterCommand::MODIFY_REFRESH && refresher) { refresher->checkAlterIsPossible(*command.refresh->as()); continue; diff --git a/src/Storages/StorageMerge.cpp b/src/Storages/StorageMerge.cpp index 80d646205bf..f954859f151 100644 --- a/src/Storages/StorageMerge.cpp +++ b/src/Storages/StorageMerge.cpp @@ -1388,11 +1388,9 @@ DatabaseTablesIteratorPtr StorageMerge::DatabaseNameOrRegexp::getDatabaseIterato { if (auto it = source_databases_and_tables->find(database_name); it != source_databases_and_tables->end()) return it->second.contains(table_name_); - else - return false; + return false; } - else - return source_table_regexp->match(table_name_); + return source_table_regexp->match(table_name_); }; return database->getTablesIterator(local_context, table_name_match); diff --git a/src/Storages/StorageMergeTree.cpp b/src/Storages/StorageMergeTree.cpp index e8bdb61d4b6..f76a0b56986 100644 --- a/src/Storages/StorageMergeTree.cpp +++ b/src/Storages/StorageMergeTree.cpp @@ -249,8 +249,8 @@ void StorageMergeTree::read( if (local_context->canUseParallelReplicasCustomKey() && settings[Setting::parallel_replicas_for_non_replicated_merge_tree] && !settings[Setting::allow_experimental_analyzer] && local_context->getClientInfo().distributed_depth == 0) { - if (auto cluster = local_context->getClusterForParallelReplicas(); - local_context->canUseParallelReplicasCustomKeyForCluster(*cluster)) + auto cluster = local_context->getClusterForParallelReplicas(); + if (local_context->canUseParallelReplicasCustomKeyForCluster(*cluster)) { auto modified_query_info = query_info; modified_query_info.cluster = std::move(cluster); @@ -265,12 +265,11 @@ void StorageMergeTree::read( local_context); return; } - else - LOG_WARNING( - log, - "Parallel replicas with custom key will not be used because cluster defined by 'cluster_for_parallel_replicas' ('{}') has " - "multiple shards", - cluster->getName()); + LOG_WARNING( + log, + "Parallel replicas with custom key will not be used because cluster defined by 'cluster_for_parallel_replicas' ('{}') has " + "multiple shards", + cluster->getName()); } const bool enable_parallel_reading = local_context->canUseParallelReplicasOnFollower() @@ -496,8 +495,7 @@ CurrentlyMergingPartsTagger::CurrentlyMergingPartsTagger( { if (is_mutation) throw Exception(ErrorCodes::NOT_ENOUGH_SPACE, "Not enough space for mutating part '{}'", future_part->parts[0]->name); - else - throw Exception(ErrorCodes::NOT_ENOUGH_SPACE, "Not enough space for merging parts"); + throw Exception(ErrorCodes::NOT_ENOUGH_SPACE, "Not enough space for merging parts"); } future_part->updatePath(storage, reserved_space.get()); @@ -1023,8 +1021,7 @@ MergeMutateSelectedEntryPtr StorageMergeTree::selectPartsToMerge( disable_reason = PreformattedMessage::create("Some part currently in a merging or mutating process"); return false; } - else - return true; + return true; } if (currently_merging_mutating_parts.contains(left) || currently_merging_mutating_parts.contains(right)) @@ -1357,13 +1354,10 @@ MergeMutateSelectedEntryPtr StorageMergeTree::selectPartsToMutate( } break; } - else - { - current_ast_elements += commands_size; - commands->insert(commands->end(), single_mutation_commands->begin(), single_mutation_commands->end()); - last_mutation_to_apply = it; - } + current_ast_elements += commands_size; + commands->insert(commands->end(), single_mutation_commands->begin(), single_mutation_commands->end()); + last_mutation_to_apply = it; } assert(commands->empty() == (last_mutation_to_apply == mutations_end_it)); @@ -1791,25 +1785,23 @@ MergeTreeDataPartPtr StorageMergeTree::outdatePart(MergeTreeTransaction * txn, c removePartsFromWorkingSet(txn, {part}, clear_without_timeout, &parts_lock); return part; } - else - { - /// Wait merges selector - std::unique_lock lock(currently_processing_in_background_mutex); - auto parts_lock = lockParts(); - auto part = getPartIfExistsUnlocked(part_name, {MergeTreeDataPartState::Active}, parts_lock); - /// It's okay, part was already removed - if (!part) - return nullptr; + /// Wait merges selector + std::unique_lock lock(currently_processing_in_background_mutex); + auto parts_lock = lockParts(); - /// Part will be "removed" by merge or mutation, it's OK in case of some - /// background cleanup processes like removing of empty parts. - if (currently_merging_mutating_parts.contains(part)) - return nullptr; + auto part = getPartIfExistsUnlocked(part_name, {MergeTreeDataPartState::Active}, parts_lock); + /// It's okay, part was already removed + if (!part) + return nullptr; - removePartsFromWorkingSet(txn, {part}, clear_without_timeout, &parts_lock); - return part; - } + /// Part will be "removed" by merge or mutation, it's OK in case of some + /// background cleanup processes like removing of empty parts. + if (currently_merging_mutating_parts.contains(part)) + return nullptr; + + removePartsFromWorkingSet(txn, {part}, clear_without_timeout, &parts_lock); + return part; } void StorageMergeTree::dropPartNoWaitNoThrow(const String & part_name) @@ -2430,9 +2422,9 @@ ActionLock StorageMergeTree::getActionLock(StorageActionBlockType action_type) { if (action_type == ActionLocks::PartsMerge) return merger_mutator.merges_blocker.cancel(); - else if (action_type == ActionLocks::PartsTTLMerge) + if (action_type == ActionLocks::PartsTTLMerge) return merger_mutator.ttl_merges_blocker.cancel(); - else if (action_type == ActionLocks::PartsMove) + if (action_type == ActionLocks::PartsMove) return parts_mover.moves_blocker.cancel(); return {}; diff --git a/src/Storages/StorageRedis.cpp b/src/Storages/StorageRedis.cpp index 80bf54e70a8..36170eb312b 100644 --- a/src/Storages/StorageRedis.cpp +++ b/src/Storages/StorageRedis.cpp @@ -237,32 +237,30 @@ Pipe StorageRedis::read( { return Pipe(std::make_shared(*this, header, max_block_size)); } - else + + if (keys->empty()) + return {}; + + Pipes pipes; + + ::sort(keys->begin(), keys->end()); + keys->erase(std::unique(keys->begin(), keys->end()), keys->end()); + + size_t num_keys = keys->size(); + size_t num_threads = std::min(num_streams, keys->size()); + + num_threads = std::min(num_threads, configuration.pool_size); + assert(num_keys <= std::numeric_limits::max()); + + for (size_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) { - if (keys->empty()) - return {}; + size_t begin = num_keys * thread_idx / num_threads; + size_t end = num_keys * (thread_idx + 1) / num_threads; - Pipes pipes; - - ::sort(keys->begin(), keys->end()); - keys->erase(std::unique(keys->begin(), keys->end()), keys->end()); - - size_t num_keys = keys->size(); - size_t num_threads = std::min(num_streams, keys->size()); - - num_threads = std::min(num_threads, configuration.pool_size); - assert(num_keys <= std::numeric_limits::max()); - - for (size_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) - { - size_t begin = num_keys * thread_idx / num_threads; - size_t end = num_keys * (thread_idx + 1) / num_threads; - - pipes.emplace_back( - std::make_shared(*this, header, keys, keys->begin() + begin, keys->begin() + end, max_block_size)); - } - return Pipe::unitePipes(std::move(pipes)); + pipes.emplace_back( + std::make_shared(*this, header, keys, keys->begin() + begin, keys->begin() + end, max_block_size)); } + return Pipe::unitePipes(std::move(pipes)); } namespace diff --git a/src/Storages/StorageReplicatedMergeTree.cpp b/src/Storages/StorageReplicatedMergeTree.cpp index fa084059611..e8bde2f4ec1 100644 --- a/src/Storages/StorageReplicatedMergeTree.cpp +++ b/src/Storages/StorageReplicatedMergeTree.cpp @@ -446,10 +446,8 @@ StorageReplicatedMergeTree::StorageReplicatedMergeTree( dropIfEmpty(); throw; } - else - { - current_zookeeper = nullptr; - } + + current_zookeeper = nullptr; } } @@ -595,8 +593,7 @@ StorageReplicatedMergeTree::StorageReplicatedMergeTree( { if (!is_first_replica && e.code == Coordination::Error::ZNONODE) throw Exception(ErrorCodes::ALL_REPLICAS_LOST, "Table {} was suddenly removed.", zookeeper_path); - else - throw; + throw; } if (!is_first_replica) @@ -689,18 +686,20 @@ void StorageReplicatedMergeTree::waitMutationToFinishOnReplicas( LOG_WARNING(log, "Replica {} was removed", replica); break; } - else if (mutation_pointer_value >= mutation_id) /// Maybe we already processed more fresh mutation + if (mutation_pointer_value >= mutation_id) /// Maybe we already processed more fresh mutation { bool mutation_killed_or_done_locally = !mutation_status || mutation_status->is_done; if (mutation_killed_or_done_locally) { LOG_TRACE(log, "Mutation {} is done because mutation pointer is {}", mutation_id, mutation_pointer_value); - break; /// (numbers like 0000000000 and 0000000001) - } - else - { - LOG_TRACE(log, "Mutation {} is done because mutation pointer is {}, but state is not updated in memory, will wait", mutation_id, mutation_pointer_value); + break; /// (numbers like 0000000000 and 0000000001) } + + LOG_TRACE( + log, + "Mutation {} is done because mutation pointer is {}, but state is not updated in memory, will wait", + mutation_id, + mutation_pointer_value); } /// Replica can become inactive, so wait with timeout, if nothing happened -> recheck it @@ -996,7 +995,7 @@ bool StorageReplicatedMergeTree::createTableIfNotExists(const StorageMetadataPtr LOG_INFO(log, "It looks like the table {} was created by another server at the same moment, will retry", zookeeper_path); continue; } - else if (code != Coordination::Error::ZOK) + if (code != Coordination::Error::ZOK) { zkutil::KeeperMultiException::check(code, ops, responses); } @@ -1393,12 +1392,12 @@ bool StorageReplicatedMergeTree::dropReplica( LOG_WARNING(logger, "Table {} is already started to be removing by another replica right now", remote_replica_path); return false; } - else if (code == Coordination::Error::ZNOTEMPTY) + if (code == Coordination::Error::ZNOTEMPTY) { LOG_WARNING(logger, "Another replica was suddenly created, will keep the table {}", remote_replica_path); return false; } - else if (code != Coordination::Error::ZOK) + if (code != Coordination::Error::ZOK) { zkutil::KeeperMultiException::check(code, ops, responses); } @@ -1485,10 +1484,13 @@ bool StorageReplicatedMergeTree::removeTableNodesFromZooKeeper(zkutil::ZooKeeper { throw Exception(ErrorCodes::LOGICAL_ERROR, "There is a race condition between creation and removal of replicated table. It's a bug"); } - else if (code == Coordination::Error::ZNOTEMPTY) + if (code == Coordination::Error::ZNOTEMPTY) { - LOG_ERROR(logger, "Table was not completely removed from ZooKeeper, {} still exists and may contain some garbage," - "but someone is removing it right now.", zookeeper_path); + LOG_ERROR( + logger, + "Table was not completely removed from ZooKeeper, {} still exists and may contain some garbage," + "but someone is removing it right now.", + zookeeper_path); } else if (code != Coordination::Error::ZOK) { @@ -1885,12 +1887,11 @@ bool StorageReplicatedMergeTree::checkPartChecksumsAndAddCommitOps( absent_replicas_paths.emplace(current_part_path); continue; } - else - { - part_found = true; - if (replica == replica_name) - part_exists_on_our_replica = true; - } + + part_found = true; + if (replica == replica_name) + part_exists_on_our_replica = true; + ReplicatedMergeTreePartHeader replica_part_header; if (part_zk_str.empty()) @@ -2322,10 +2323,14 @@ bool StorageReplicatedMergeTree::executeFetch(LogEntry & entry, bool need_to_che queue.removeFailedQuorumPart(part_info); return true; } - else if (code == Coordination::Error::ZBADVERSION || code == Coordination::Error::ZNONODE || code == Coordination::Error::ZNODEEXISTS) + if (code == Coordination::Error::ZBADVERSION || code == Coordination::Error::ZNONODE + || code == Coordination::Error::ZNODEEXISTS) { - LOG_DEBUG(log, "State was changed or isn't expected when trying to mark quorum for part {} as failed. Code: {}", - entry.new_part_name, code); + LOG_DEBUG( + log, + "State was changed or isn't expected when trying to mark quorum for part {} as failed. Code: {}", + entry.new_part_name, + code); } else throw Coordination::Exception(code); @@ -3109,29 +3114,28 @@ void StorageReplicatedMergeTree::cloneReplica(const String & source_replica, Coo { break; } - else if (rc == Coordination::Error::ZNODEEXISTS) + if (rc == Coordination::Error::ZNODEEXISTS) { - throw Exception(ErrorCodes::REPLICA_STATUS_CHANGED, - "Can not clone replica, because the {} updated to new ClickHouse version", source_replica); + throw Exception( + ErrorCodes::REPLICA_STATUS_CHANGED, + "Can not clone replica, because the {} updated to new ClickHouse version", + source_replica); } - else if (responses[1]->error == Coordination::Error::ZBADVERSION) + if (responses[1]->error == Coordination::Error::ZBADVERSION) { /// If is_lost node version changed than source replica also lost, /// so we cannot clone from it. - throw Exception(ErrorCodes::REPLICA_STATUS_CHANGED, "Can not clone replica, because the {} became lost", - source_replica); + throw Exception(ErrorCodes::REPLICA_STATUS_CHANGED, "Can not clone replica, because the {} became lost", source_replica); } - else if (responses.back()->error == Coordination::Error::ZBADVERSION) + if (responses.back()->error == Coordination::Error::ZBADVERSION) { /// If source replica's log_pointer changed than we probably read /// stale state of /queue and have to try one more time. LOG_WARNING(log, "Log pointer of source replica {} changed while we loading queue nodes. Will retry.", source_replica); continue; } - else - { - zkutil::KeeperMultiException::check(rc, ops, responses); - } + + zkutil::KeeperMultiException::check(rc, ops, responses); } ::sort(source_queue_names.begin(), source_queue_names.end()); @@ -3465,7 +3469,7 @@ void StorageReplicatedMergeTree::cloneMetadataIfNeeded(const String & source_rep Coordination::Error code = zookeeper->tryMulti(ops, responses, /* check_session_valid */ true); if (code == Coordination::Error::ZOK) break; - else if (code == Coordination::Error::ZBADVERSION) + if (code == Coordination::Error::ZBADVERSION) LOG_WARNING(log, "Metadata of replica {} was changed", source_path); else zkutil::KeeperMultiException::check(code, ops, responses); @@ -3564,7 +3568,7 @@ void StorageReplicatedMergeTree::cloneReplicaIfNeeded(zkutil::ZooKeeperPtr zooke LOG_INFO(log, "Not cloning {}, cannot get '/is_lost': {}", source_replica_name, get_is_lost.error); continue; } - else if (get_is_lost.data != "0") + if (get_is_lost.data != "0") { LOG_INFO(log, "Not cloning {}, it's lost", source_replica_name); continue; @@ -3775,27 +3779,24 @@ bool StorageReplicatedMergeTree::scheduleDataProcessingJob(BackgroundJobsAssigne }, common_assignee_trigger, getStorageID())); return true; } - else if (job_type == LogEntry::MERGE_PARTS) + if (job_type == LogEntry::MERGE_PARTS) { auto task = std::make_shared(selected_entry, *this, common_assignee_trigger); assignee.scheduleMergeMutateTask(task); return true; } - else if (job_type == LogEntry::MUTATE_PART) + if (job_type == LogEntry::MUTATE_PART) { auto task = std::make_shared(selected_entry, *this, common_assignee_trigger); assignee.scheduleMergeMutateTask(task); return true; } - else - { - assignee.scheduleCommonTask(std::make_shared( - [this, selected_entry] () mutable - { - return processQueueEntry(selected_entry); - }, common_assignee_trigger, getStorageID()), /* need_trigger */ true); - return true; - } + + assignee.scheduleCommonTask( + std::make_shared( + [this, selected_entry]() mutable { return processQueueEntry(selected_entry); }, common_assignee_trigger, getStorageID()), + /* need_trigger */ true); + return true; } @@ -4467,10 +4468,9 @@ void StorageReplicatedMergeTree::waitForUniquePartsToBeFetchedByOtherReplicas(St LOG_INFO(log, "Will not wait for unique parts to be fetched because we don't have any unique parts"); return; } - else - { - LOG_INFO(log, "Will wait for {} unique parts to be fetched", unique_parts_set.size()); - } + + LOG_INFO(log, "Will wait for {} unique parts to be fetched", unique_parts_set.size()); + auto wait_predicate = [&] () -> bool { @@ -4705,43 +4705,43 @@ void StorageReplicatedMergeTree::updateQuorum(const String & part_name, bool is_ { break; } - else if (code == Coordination::Error::ZNONODE) + if (code == Coordination::Error::ZNONODE) { /// The quorum has already been achieved. break; } - else if (code == Coordination::Error::ZBADVERSION) + if (code == Coordination::Error::ZBADVERSION) { /// Node was updated meanwhile. We must re-read it and repeat all the actions. continue; } - else - throw Coordination::Exception::fromPath(code, quorum_status_path); + throw Coordination::Exception::fromPath(code, quorum_status_path); } - else - { - LOG_TRACE(log, "Quorum {} still not satisfied (have only {} of {} replicas), updating node", - quorum_status_path, quorum_entry.replicas.size(), quorum_entry.required_number_of_replicas); - /// We update the node, registering there one more replica. - auto code = zookeeper->trySet(quorum_status_path, quorum_entry.toString(), stat.version); - if (code == Coordination::Error::ZOK) - { - break; - } - else if (code == Coordination::Error::ZNONODE) - { - /// The quorum has already been achieved. - break; - } - else if (code == Coordination::Error::ZBADVERSION) - { - /// Node was updated meanwhile. We must re-read it and repeat all the actions. - continue; - } - else - throw Coordination::Exception::fromPath(code, quorum_status_path); + LOG_TRACE( + log, + "Quorum {} still not satisfied (have only {} of {} replicas), updating node", + quorum_status_path, + quorum_entry.replicas.size(), + quorum_entry.required_number_of_replicas); + /// We update the node, registering there one more replica. + auto code = zookeeper->trySet(quorum_status_path, quorum_entry.toString(), stat.version); + + if (code == Coordination::Error::ZOK) + { + break; } + if (code == Coordination::Error::ZNONODE) + { + /// The quorum has already been achieved. + break; + } + if (code == Coordination::Error::ZBADVERSION) + { + /// Node was updated meanwhile. We must re-read it and repeat all the actions. + continue; + } + throw Coordination::Exception::fromPath(code, quorum_status_path); } } @@ -4789,19 +4789,18 @@ void StorageReplicatedMergeTree::cleanLastPartNode(const String & partition_id) LOG_DEBUG(log, "Last parent node for partition {} is cleaned up", partition_id); break; } - else if (code == Coordination::Error::ZNONODE) + if (code == Coordination::Error::ZNONODE) { /// Node is deleted. It is impossible, but it is Ok. LOG_WARNING(log, "The last part node {} was deleted", quorum_last_part_path); break; } - else if (code == Coordination::Error::ZBADVERSION) + if (code == Coordination::Error::ZBADVERSION) { /// Node was updated meanwhile. We must re-read it and repeat all the actions. continue; } - else - throw Coordination::Exception::fromPath(code, quorum_last_part_path); + throw Coordination::Exception::fromPath(code, quorum_last_part_path); } } @@ -5559,8 +5558,8 @@ void StorageReplicatedMergeTree::read( if (local_context->canUseParallelReplicasCustomKey() && !settings[Setting::allow_experimental_analyzer] && local_context->getClientInfo().distributed_depth == 0) { - if (auto cluster = local_context->getClusterForParallelReplicas(); - local_context->canUseParallelReplicasCustomKeyForCluster(*cluster)) + auto cluster = local_context->getClusterForParallelReplicas(); + if (local_context->canUseParallelReplicasCustomKeyForCluster(*cluster)) { auto modified_query_info = query_info; modified_query_info.cluster = std::move(cluster); @@ -5575,12 +5574,11 @@ void StorageReplicatedMergeTree::read( local_context); return; } - else - LOG_WARNING( - log, - "Parallel replicas with custom key will not be used because cluster defined by 'cluster_for_parallel_replicas' ('{}') has " - "multiple shards", - cluster->getName()); + LOG_WARNING( + log, + "Parallel replicas with custom key will not be used because cluster defined by 'cluster_for_parallel_replicas' ('{}') has " + "multiple shards", + cluster->getName()); } readLocalImpl(query_plan, column_names, storage_snapshot, query_info, local_context, max_block_size, num_streams); } @@ -5843,10 +5841,13 @@ std::optional StorageReplicatedMergeTree::distributedWrite(const { return distributedWriteFromClusterStorage(src_distributed, query, local_context); } - else if (local_context->getClientInfo().distributed_depth == 0) + if (local_context->getClientInfo().distributed_depth == 0) { - throw Exception(ErrorCodes::BAD_ARGUMENTS, "Parallel distributed INSERT SELECT is not possible. Reason: distributed " - "reading into Replicated table is supported only from *Cluster table functions, but got {} storage", src_storage->getName()); + throw Exception( + ErrorCodes::BAD_ARGUMENTS, + "Parallel distributed INSERT SELECT is not possible. Reason: distributed " + "reading into Replicated table is supported only from *Cluster table functions, but got {} storage", + src_storage->getName()); } return {}; @@ -5968,14 +5969,12 @@ bool StorageReplicatedMergeTree::optimize( waitForProcessingQueue(wait_timeout, SyncReplicaMode::DEFAULT, {}); continue; } - else - { - constexpr const char * message_fmt = "Cannot select parts for optimization: {}"; - assert(disable_reason.text != unknown_disable_reason); - if (!partition_id.empty()) - disable_reason.text += fmt::format(" (in partition {})", partition_id); - return handle_noop(message_fmt, disable_reason.text); - } + + constexpr const char * message_fmt = "Cannot select parts for optimization: {}"; + assert(disable_reason.text != unknown_disable_reason); + if (!partition_id.empty()) + disable_reason.text += fmt::format(" (in partition {})", partition_id); + return handle_noop(message_fmt, disable_reason.text); } ReplicatedMergeTreeLogEntryData merge_entry; @@ -6137,21 +6136,19 @@ PartitionBlockNumbersHolder StorageReplicatedMergeTree::allocateBlockNumbersInAf auto block_number = block_number_holder->getNumber(); /// Avoid possible UB due to std::move return {{{affected_partition_id, block_number}}, std::move(block_number_holder)}; } - else + + /// TODO: Implement optimal block number acquisition algorithm in multiple (but not all) partitions + EphemeralLocksInAllPartitions lock_holder( + fs::path(zookeeper_path) / "block_numbers", "block-", fs::path(zookeeper_path) / "temp", *zookeeper); + + PartitionBlockNumbersHolder::BlockNumbersType block_numbers; + for (const auto & lock : lock_holder.getLocks()) { - /// TODO: Implement optimal block number acquisition algorithm in multiple (but not all) partitions - EphemeralLocksInAllPartitions lock_holder( - fs::path(zookeeper_path) / "block_numbers", "block-", fs::path(zookeeper_path) / "temp", *zookeeper); - - PartitionBlockNumbersHolder::BlockNumbersType block_numbers; - for (const auto & lock : lock_holder.getLocks()) - { - if (mutation_affected_partition_ids.empty() || mutation_affected_partition_ids.contains(lock.partition_id)) - block_numbers[lock.partition_id] = lock.number; - } - - return {std::move(block_numbers), std::move(lock_holder)}; + if (mutation_affected_partition_ids.empty() || mutation_affected_partition_ids.contains(lock.partition_id)) + block_numbers[lock.partition_id] = lock.number; } + + return {std::move(block_numbers), std::move(lock_holder)}; } @@ -6417,27 +6414,27 @@ void StorageReplicatedMergeTree::alter( } break; } - else if (rc == Coordination::Error::ZBADVERSION) + if (rc == Coordination::Error::ZBADVERSION) { if (results[0]->error != Coordination::Error::ZOK) - throw Exception(ErrorCodes::CANNOT_ASSIGN_ALTER, - "Metadata on replica is not up to date with common metadata in Zookeeper. " - "It means that this replica still not applied some of previous alters." - " Probably too many alters executing concurrently (highly not recommended). " - "You can retry this error"); + throw Exception( + ErrorCodes::CANNOT_ASSIGN_ALTER, + "Metadata on replica is not up to date with common metadata in Zookeeper. " + "It means that this replica still not applied some of previous alters." + " Probably too many alters executing concurrently (highly not recommended). " + "You can retry this error"); /// Cannot retry automatically, because some zookeeper ops were lost on the first attempt. Will retry on DDLWorker-level. if (query_context->getZooKeeperMetadataTransaction()) - throw Exception(ErrorCodes::CANNOT_ASSIGN_ALTER, - "Cannot execute alter, because mutations version was suddenly changed due " - "to concurrent alter"); + throw Exception( + ErrorCodes::CANNOT_ASSIGN_ALTER, + "Cannot execute alter, because mutations version was suddenly changed due " + "to concurrent alter"); continue; } - else - { - throw Coordination::Exception::fromMessage(rc, "Alter cannot be assigned because of Zookeeper error"); - } + + throw Coordination::Exception::fromMessage(rc, "Alter cannot be assigned because of Zookeeper error"); } table_lock_holder.unlock(); @@ -7084,12 +7081,13 @@ bool StorageReplicatedMergeTree::tryWaitForReplicaToProcessLogEntry( queue_entry_to_wait_for = entry_name; break; } - else if (!entry.log_entry_id.empty()) + if (!entry.log_entry_id.empty()) { /// Check if the id matches rather than just contents. This entry /// might have been written by different ClickHouse versions and /// it is hard to guarantee same text representation. - ReplicatedMergeTreeLogEntryData queue_entry = *ReplicatedMergeTreeLogEntry::parse(queue_entry_str, queue_entry_stat, format_version); + ReplicatedMergeTreeLogEntryData queue_entry + = *ReplicatedMergeTreeLogEntry::parse(queue_entry_str, queue_entry_stat, format_version); if (entry.log_entry_id == queue_entry.log_entry_id) { queue_entry_to_wait_for = entry_name; @@ -7224,23 +7222,21 @@ time_t StorageReplicatedMergeTree::getAbsoluteDelay() const /// As we have no info about the current state of replication log, return effectively infinite delay. return current_time; } - else if (min_unprocessed_insert_time) + if (min_unprocessed_insert_time) { /// There are some unprocessed insert entries in queue. return (current_time > min_unprocessed_insert_time) ? (current_time - min_unprocessed_insert_time) : 0; } - else if (queue_update_start_time > queue_update_finish_time) + if (queue_update_start_time > queue_update_finish_time) { /// Queue is empty, but there are some in-flight or failed queue update attempts /// (likely because of problems with connecting to ZooKeeper). /// Return the time passed since last attempt. return (current_time > queue_update_start_time) ? (current_time - queue_update_start_time) : 0; } - else - { - /// Everything is up-to-date. - return 0; - } + + /// Everything is up-to-date. + return 0; } void StorageReplicatedMergeTree::getReplicaDelays(time_t & out_absolute_delay, time_t & out_relative_delay) @@ -7645,18 +7641,18 @@ void StorageReplicatedMergeTree::mutate(const MutationCommands & commands, Conte mutation_entry.znode_name, mutation_entry.getBlockNumbersForLogs()); break; } - else if (rc == Coordination::Error::ZBADVERSION) + if (rc == Coordination::Error::ZBADVERSION) { /// Cannot retry automatically, because some zookeeper ops were lost on the first attempt. Will retry on DDLWorker-level. if (query_context->getZooKeeperMetadataTransaction()) - throw Exception(ErrorCodes::CANNOT_ASSIGN_ALTER, - "Cannot execute alter, because mutations version was suddenly changed due " - "to concurrent alter"); + throw Exception( + ErrorCodes::CANNOT_ASSIGN_ALTER, + "Cannot execute alter, because mutations version was suddenly changed due " + "to concurrent alter"); LOG_TRACE(log, "Version conflict when trying to create a mutation node, retrying..."); continue; } - else - throw Coordination::Exception::fromMessage(rc, "Unable to create a mutation znode"); + throw Coordination::Exception::fromMessage(rc, "Unable to create a mutation znode"); } merge_selecting_task->schedule(); @@ -8651,8 +8647,7 @@ void StorageReplicatedMergeTree::movePartitionToTable(const StoragePtr & dest_ta Coordination::Error code = zookeeper->tryMulti(ops, op_results); if (code == Coordination::Error::ZBADVERSION) continue; - else - zkutil::KeeperMultiException::check(code, ops, op_results); + zkutil::KeeperMultiException::check(code, ops, op_results); parts_holder = getDataPartsVectorInPartitionForInternalUsage(MergeTreeDataPartState::Active, drop_range.partition_id, &src_data_parts_lock); /// We ignore the list of parts returned from the function below because we cannot remove them from zk @@ -9074,13 +9069,15 @@ bool StorageReplicatedMergeTree::dropPartImpl( LOG_TRACE(log, "A new log entry appeared while trying to commit DROP RANGE. Retry."); continue; } - else if (rc == Coordination::Error::ZNONODE) + if (rc == Coordination::Error::ZNONODE) { - LOG_TRACE(log, "Other replica already removing same part {} or part deduplication node was removed by background thread. Retry.", part_name); + LOG_TRACE( + log, + "Other replica already removing same part {} or part deduplication node was removed by background thread. Retry.", + part_name); continue; } - else - zkutil::KeeperMultiException::check(rc, ops, responses); + zkutil::KeeperMultiException::check(rc, ops, responses); String log_znode_path = dynamic_cast(*responses[clear_block_ops_size + 1]).path_created; entry.znode_name = log_znode_path.substr(log_znode_path.find_last_of('/') + 1); @@ -9296,7 +9293,7 @@ void StorageReplicatedMergeTree::checkBrokenDisks() for (auto disk_it = disks.rbegin(); disk_it != disks.rend(); ++disk_it) { - auto disk_ptr = *disk_it; + const auto & disk_ptr = *disk_it; if (disk_ptr->isBroken()) { { @@ -9317,17 +9314,12 @@ void StorageReplicatedMergeTree::checkBrokenDisks() } continue; } - else + { - { - std::lock_guard lock(last_broken_disks_mutex); - if (last_broken_disks.erase(disk_ptr->getName()) > 0) - LOG_INFO( - log, - "Disk {} with path {} is recovered. Exclude it from last_broken_disks", - disk_ptr->getName(), - disk_ptr->getPath()); - } + std::lock_guard lock(last_broken_disks_mutex); + if (last_broken_disks.erase(disk_ptr->getName()) > 0) + LOG_INFO( + log, "Disk {} with path {} is recovered. Exclude it from last_broken_disks", disk_ptr->getName(), disk_ptr->getPath()); } } } @@ -9630,10 +9622,8 @@ StorageReplicatedMergeTree::unlockSharedData(const IMergeTreeDataPart & part, co LOG_TRACE(log, "Part {} has more than zero local references ({}), blobs cannot be removed", part.name, ref_count); return std::make_pair(false, NameSet{}); } - else - { - LOG_TRACE(log, "Part {} local references is zero, will check blobs can be removed in zookeeper", part.name); - } + + LOG_TRACE(log, "Part {} local references is zero, will check blobs can be removed in zookeeper", part.name); } else { @@ -9856,10 +9846,12 @@ std::pair StorageReplicatedMergeTree::unlockSharedDataByID( LOG_INFO(logger, "Lock on path {} for part {} doesn't exist, refuse to remove blobs", zookeeper_part_replica_node, part_name); return {false, {}}; } - else - { - LOG_INFO(logger, "Lock on path {} for part {} doesn't exist, but we don't have mutation parent, can remove blobs", zookeeper_part_replica_node, part_name); - } + + LOG_INFO( + logger, + "Lock on path {} for part {} doesn't exist, but we don't have mutation parent, can remove blobs", + zookeeper_part_replica_node, + part_name); } else { @@ -9877,10 +9869,9 @@ std::pair StorageReplicatedMergeTree::unlockSharedDataByID( part_has_no_more_locks = false; continue; } - else - { - LOG_TRACE(logger, "No more children left for {}, will try to remove the whole node", zookeeper_part_uniq_node); - } + + LOG_TRACE(logger, "No more children left for {}, will try to remove the whole node", zookeeper_part_uniq_node); + auto error_code = zookeeper_ptr->tryRemove(zookeeper_part_uniq_node); @@ -10382,7 +10373,7 @@ bool StorageReplicatedMergeTree::createEmptyPartInsteadOfLost(zkutil::ZooKeeperP transaction.commit(); break; } - else if (code == Coordination::Error::ZBADVERSION) + if (code == Coordination::Error::ZBADVERSION) { LOG_INFO(log, "Looks like log was updated or new replica appeared while creating new empty part, will retry"); } @@ -10472,7 +10463,7 @@ void StorageReplicatedMergeTree::createZeroCopyLockNode( created = true; break; } - else if (mode == zkutil::CreateMode::Persistent) + if (mode == zkutil::CreateMode::Persistent) { if (error == Coordination::Error::ZNONODE) continue; @@ -10501,7 +10492,10 @@ void StorageReplicatedMergeTree::createZeroCopyLockNode( size_t failed_op = zkutil::getFailedOpIndex(error, responses); if (ops[failed_op]->getPath() == zookeeper_node) { - LOG_WARNING(getLogger("ZeroCopyLocks"), "Replacing persistent lock with ephemeral for path {}. It can happen only in case of local part loss", zookeeper_node); + LOG_WARNING( + getLogger("ZeroCopyLocks"), + "Replacing persistent lock with ephemeral for path {}. It can happen only in case of local part loss", + zookeeper_node); replace_existing_lock = true; continue; } diff --git a/src/Storages/StorageURL.cpp b/src/Storages/StorageURL.cpp index 80c07658055..6dea6436a5a 100644 --- a/src/Storages/StorageURL.cpp +++ b/src/Storages/StorageURL.cpp @@ -1357,19 +1357,17 @@ SinkToStoragePtr IStorageURLBase::write(const ASTPtr & query, const StorageMetad headers, http_method); } - else - { - return std::make_shared( - uri, - format_name, - format_settings, - metadata_snapshot->getSampleBlock(), - context, - getHTTPTimeouts(context), - compression_method, - headers, - http_method); - } + + return std::make_shared( + uri, + format_name, + format_settings, + metadata_snapshot->getSampleBlock(), + context, + getHTTPTimeouts(context), + compression_method, + headers, + http_method); } SchemaCache & IStorageURLBase::getSchemaCache(const ContextPtr & context) diff --git a/src/Storages/System/StorageSystemAsyncLoader.cpp b/src/Storages/System/StorageSystemAsyncLoader.cpp index a7ffa282429..38bf5e93bbe 100644 --- a/src/Storages/System/StorageSystemAsyncLoader.cpp +++ b/src/Storages/System/StorageSystemAsyncLoader.cpp @@ -40,8 +40,7 @@ namespace { if (time_point == TimePoint{}) return {}; - else - return timeInMicroseconds(time_point); + return timeInMicroseconds(time_point); } } diff --git a/src/Storages/System/StorageSystemPartsBase.cpp b/src/Storages/System/StorageSystemPartsBase.cpp index 8d48d65ae13..5ba2089ac14 100644 --- a/src/Storages/System/StorageSystemPartsBase.cpp +++ b/src/Storages/System/StorageSystemPartsBase.cpp @@ -148,7 +148,7 @@ StoragesInfoStream::StoragesInfoStream(std::optional filter_by_datab for (size_t i = 0; i < rows; ++i) { String database_name = (*database_column_for_filter)[i].safeGet(); - const DatabasePtr database = databases.at(database_name); + const DatabasePtr & database = databases.at(database_name); offsets[i] = i ? offsets[i - 1] : 0; for (auto iterator = database->getTablesIterator(context); iterator->isValid(); iterator->next()) diff --git a/src/Storages/System/StorageSystemStackTrace.cpp b/src/Storages/System/StorageSystemStackTrace.cpp index 0151bb83dde..e79c42f00cc 100644 --- a/src/Storages/System/StorageSystemStackTrace.cpp +++ b/src/Storages/System/StorageSystemStackTrace.cpp @@ -168,8 +168,7 @@ bool wait(int timeout_ms) { if (notification_num == sequence_num.load(std::memory_order_relaxed)) return true; - else - continue; /// Drain delayed notifications. + continue; /// Drain delayed notifications. } throw Exception(ErrorCodes::LOGICAL_ERROR, "Read wrong number of bytes from pipe"); diff --git a/src/Storages/TimeSeries/PrometheusRemoteReadProtocol.cpp b/src/Storages/TimeSeries/PrometheusRemoteReadProtocol.cpp index d6d258f5ff6..52fa24f48e0 100644 --- a/src/Storages/TimeSeries/PrometheusRemoteReadProtocol.cpp +++ b/src/Storages/TimeSeries/PrometheusRemoteReadProtocol.cpp @@ -103,14 +103,22 @@ namespace if (type == prometheus::LabelMatcher::EQ) return makeASTFunction("equals", makeASTLabelName(label_name, tags_table_id, column_name_by_tag_name), std::make_shared(label_value)); - else if (type == prometheus::LabelMatcher::NEQ) - return makeASTFunction("notEquals", makeASTLabelName(label_name, tags_table_id, column_name_by_tag_name), std::make_shared(label_value)); - else if (type == prometheus::LabelMatcher::RE) - return makeASTFunction("match", makeASTLabelName(label_name, tags_table_id, column_name_by_tag_name), std::make_shared(label_value)); - else if (type == prometheus::LabelMatcher::NRE) - return makeASTFunction("not", makeASTFunction("match", makeASTLabelName(label_name, tags_table_id, column_name_by_tag_name), std::make_shared(label_value))); - else - throw Exception(ErrorCodes::BAD_REQUEST_PARAMETER, "Unexpected type of label matcher: {}", type); + if (type == prometheus::LabelMatcher::NEQ) + return makeASTFunction( + "notEquals", + makeASTLabelName(label_name, tags_table_id, column_name_by_tag_name), + std::make_shared(label_value)); + if (type == prometheus::LabelMatcher::RE) + return makeASTFunction( + "match", makeASTLabelName(label_name, tags_table_id, column_name_by_tag_name), std::make_shared(label_value)); + if (type == prometheus::LabelMatcher::NRE) + return makeASTFunction( + "not", + makeASTFunction( + "match", + makeASTLabelName(label_name, tags_table_id, column_name_by_tag_name), + std::make_shared(label_value))); + throw Exception(ErrorCodes::BAD_REQUEST_PARAMETER, "Unexpected type of label matcher: {}", type); } /// Makes an AST checking that tags match a specified label matcher and that timestamp is in range [min_timestamp_ms, max_timestamp_ms]. diff --git a/src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp b/src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp index 702d058ee79..3be5e8d5c39 100644 --- a/src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp +++ b/src/Storages/TimeSeries/PrometheusRemoteWriteProtocol.cpp @@ -3,6 +3,8 @@ #include "config.h" #if USE_PROMETHEUS_PROTOBUFS +#include + #include #include #include @@ -65,9 +67,11 @@ namespace { if (label_name == previous_label_name) throw Exception(ErrorCodes::ILLEGAL_TIME_SERIES_TAGS, "Found duplicate label {}", label_name); - else - throw Exception(ErrorCodes::ILLEGAL_TIME_SERIES_TAGS, "Label names are not sorted in lexicographical order ({} > {})", - previous_label_name, label_name); + throw Exception( + ErrorCodes::ILLEGAL_TIME_SERIES_TAGS, + "Label names are not sorted in lexicographical order ({} > {})", + previous_label_name, + label_name); } } } @@ -158,10 +162,9 @@ namespace { if (scale == 3) return timestamp_ms; - else if (scale > 3) + if (scale > 3) return timestamp_ms * DecimalUtils::scaleMultiplier(scale - 3); - else - return timestamp_ms / DecimalUtils::scaleMultiplier(3 - scale); + return timestamp_ms / DecimalUtils::scaleMultiplier(3 - scale); } /// Finds min time and max time in a time series. @@ -173,10 +176,8 @@ namespace for (const auto & sample : samples) { Int64 timestamp = sample.timestamp(); - if (timestamp < min_time) - min_time = timestamp; - if (timestamp > max_time) - max_time = timestamp; + min_time = std::min(timestamp, min_time); + max_time = std::max(timestamp, max_time); } return {min_time, max_time}; } diff --git a/src/Storages/TimeSeries/TimeSeriesDefinitionNormalizer.cpp b/src/Storages/TimeSeries/TimeSeriesDefinitionNormalizer.cpp index 746a6a28274..253a80e22de 100644 --- a/src/Storages/TimeSeries/TimeSeriesDefinitionNormalizer.cpp +++ b/src/Storages/TimeSeries/TimeSeriesDefinitionNormalizer.cpp @@ -174,8 +174,7 @@ void TimeSeriesDefinitionNormalizer::addMissingColumns(ASTCreateQuery & create) { if (type->name == "Nullable") return type; - else - return makeASTDataType("Nullable", type); + return makeASTDataType("Nullable", type); }; /// Add missing columns for the "data" table. @@ -319,26 +318,31 @@ ASTPtr TimeSeriesDefinitionNormalizer::chooseIDAlgorithm(const ASTColumnDeclarat { return make_hash_function("sipHash64"); } - else if (id_type_which.isFixedString() && typeid_cast(*id_type).getN() == 16) + if (id_type_which.isFixedString() && typeid_cast(*id_type).getN() == 16) { return make_hash_function("sipHash128"); } - else if (id_type_which.isUUID()) + if (id_type_which.isUUID()) { return makeASTFunction("reinterpretAsUUID", make_hash_function("sipHash128")); } - else if (id_type_which.isUInt128()) + if (id_type_which.isUInt128()) { return makeASTFunction("reinterpretAsUInt128", make_hash_function("sipHash128")); } - else - { - throw Exception(ErrorCodes::INCOMPATIBLE_COLUMNS, "{}: The DEFAULT expression for column {} must contain an expression " - "which will be used to calculate the identifier of each time series: {} {} DEFAULT ... " - "If the DEFAULT expression is not specified then it can be chosen implicitly but only if the column type is one of these: UInt64, UInt128, UUID. " - "For type {} the DEFAULT expression can't be chosen automatically, so please specify it explicitly", - time_series_storage_id.getNameForLogs(), id_column.name, id_column.name, id_type->getName(), id_type->getName()); - } + + throw Exception( + ErrorCodes::INCOMPATIBLE_COLUMNS, + "{}: The DEFAULT expression for column {} must contain an expression " + "which will be used to calculate the identifier of each time series: {} {} DEFAULT ... " + "If the DEFAULT expression is not specified then it can be chosen implicitly but only if the column type is one of these: " + "UInt64, UInt128, UUID. " + "For type {} the DEFAULT expression can't be chosen automatically, so please specify it explicitly", + time_series_storage_id.getNameForLogs(), + id_column.name, + id_column.name, + id_type->getName(), + id_type->getName()); } diff --git a/src/Storages/Utils.cpp b/src/Storages/Utils.cpp index ff73888e19d..bd03a96c7cc 100644 --- a/src/Storages/Utils.cpp +++ b/src/Storages/Utils.cpp @@ -18,13 +18,11 @@ namespace DB { return CurrentMetrics::AttachedView; } - else if (storage->isDictionary()) + if (storage->isDictionary()) { return CurrentMetrics::AttachedDictionary; } - else - { - return CurrentMetrics::AttachedTable; - } + + return CurrentMetrics::AttachedTable; } } diff --git a/src/Storages/VirtualColumnUtils.cpp b/src/Storages/VirtualColumnUtils.cpp index d142988804b..706950f32cf 100644 --- a/src/Storages/VirtualColumnUtils.cpp +++ b/src/Storages/VirtualColumnUtils.cpp @@ -416,7 +416,7 @@ static const ActionsDAG::Node * splitFilterNodeForAllowedInputs( return &node_copy; } - else if (node->function_base->getName() == "or") + if (node->function_base->getName() == "or") { auto & node_copy = additional_nodes.emplace_back(*node); for (auto & child : node_copy.children) @@ -425,7 +425,7 @@ static const ActionsDAG::Node * splitFilterNodeForAllowedInputs( return &node_copy; } - else if (node->function_base->getName() == "indexHint") + if (node->function_base->getName() == "indexHint") { if (const auto * adaptor = typeid_cast(node->function_base.get())) { @@ -444,7 +444,8 @@ static const ActionsDAG::Node * splitFilterNodeForAllowedInputs( if (atoms.size() > 1) { - FunctionOverloadResolverPtr func_builder_and = std::make_unique(std::make_shared()); + FunctionOverloadResolverPtr func_builder_and + = std::make_unique(std::make_shared()); res = &index_hint_dag.addFunction(func_builder_and, atoms, {}); } diff --git a/src/Storages/WindowView/StorageWindowView.cpp b/src/Storages/WindowView/StorageWindowView.cpp index 467015145f3..22eb7aaee9c 100644 --- a/src/Storages/WindowView/StorageWindowView.cpp +++ b/src/Storages/WindowView/StorageWindowView.cpp @@ -235,12 +235,10 @@ namespace /// tuple(windowID(timestamp, toIntervalSecond('5'))) return; } - else - { - /// windowID(timestamp, toIntervalSecond('5')) -> identifier. - /// and other... - node_ptr = std::make_shared(node.getColumnName()); - } + + /// windowID(timestamp, toIntervalSecond('5')) -> identifier. + /// and other... + node_ptr = std::make_shared(node.getColumnName()); } static void visit(const ASTIdentifier & node, ASTPtr & node_ptr, Data & data) @@ -409,13 +407,11 @@ UInt32 StorageWindowView::getCleanupBound() return 0; if (is_proctime) return max_fired_watermark; - else - { - auto w_bound = max_fired_watermark; - if (allowed_lateness) - w_bound = addTime(w_bound, lateness_kind, -lateness_num_units, *time_zone); - return getWindowLowerBound(w_bound); - } + + auto w_bound = max_fired_watermark; + if (allowed_lateness) + w_bound = addTime(w_bound, lateness_kind, -lateness_num_units, *time_zone); + return getWindowLowerBound(w_bound); } ASTPtr StorageWindowView::getCleanupQuery() @@ -926,12 +922,9 @@ UInt32 StorageWindowView::getWindowLowerBound(UInt32 time_sec) { \ if (is_tumble) \ return ToStartOfTransform::execute(time_sec, window_num_units, *time_zone); \ - else \ - {\ - UInt32 w_start = ToStartOfTransform::execute(time_sec, hop_num_units, *time_zone); \ - UInt32 w_end = AddTime::execute(w_start, hop_num_units, *time_zone);\ - return AddTime::execute(w_end, -window_num_units, *time_zone);\ - }\ + UInt32 w_start = ToStartOfTransform::execute(time_sec, hop_num_units, *time_zone); \ + UInt32 w_end = AddTime::execute(w_start, hop_num_units, *time_zone);\ + return AddTime::execute(w_end, -window_num_units, *time_zone);\ } CASE_WINDOW_KIND(Second) CASE_WINDOW_KIND(Minute) diff --git a/src/Storages/WindowView/WindowViewSource.h b/src/Storages/WindowView/WindowViewSource.h index 74720bf8074..d055264fffb 100644 --- a/src/Storages/WindowView/WindowViewSource.h +++ b/src/Storages/WindowView/WindowViewSource.h @@ -59,10 +59,8 @@ protected: {DataTypeDateTime(window_view_timezone).createColumnConst(block.rows(), watermark)->convertToFullColumnIfConst()}, block.rows()); } - else - { - return Chunk(block.getColumns(), block.rows()); - } + + return Chunk(block.getColumns(), block.rows()); } std::pair generateImpl() @@ -100,11 +98,9 @@ protected: blocks_with_watermark.pop_front(); return res; } - else - { - last_heartbeat_timestamp_usec = static_cast(Poco::Timestamp().epochMicroseconds()); - return {getHeader(), 0}; - } + + last_heartbeat_timestamp_usec = static_cast(Poco::Timestamp().epochMicroseconds()); + return {getHeader(), 0}; } private: diff --git a/src/Storages/buildQueryTreeForShard.cpp b/src/Storages/buildQueryTreeForShard.cpp index 28e82abbec0..d7387c51878 100644 --- a/src/Storages/buildQueryTreeForShard.cpp +++ b/src/Storages/buildQueryTreeForShard.cpp @@ -368,11 +368,12 @@ QueryTreeNodePtr buildQueryTreeForShard(const PlannerContextPtr & planner_contex replacement_map.emplace(join_right_table_expression.get(), std::move(temporary_table_expression_node)); continue; } - else if (auto * in_function_node = global_in_or_join_node.query_node->as()) + if (auto * in_function_node = global_in_or_join_node.query_node->as()) { auto & in_function_subquery_node = in_function_node->getArguments().getNodes().at(1); auto in_function_node_type = in_function_subquery_node->getNodeType(); - if (in_function_node_type != QueryTreeNodeType::QUERY && in_function_node_type != QueryTreeNodeType::UNION && in_function_node_type != QueryTreeNodeType::TABLE) + if (in_function_node_type != QueryTreeNodeType::QUERY && in_function_node_type != QueryTreeNodeType::UNION + && in_function_node_type != QueryTreeNodeType::TABLE) continue; auto & temporary_table_expression_node = global_in_temporary_tables[in_function_subquery_node]; @@ -380,18 +381,19 @@ QueryTreeNodePtr buildQueryTreeForShard(const PlannerContextPtr & planner_contex { auto subquery_to_execute = in_function_subquery_node; if (subquery_to_execute->as()) - subquery_to_execute = buildSubqueryToReadColumnsFromTableExpression(subquery_to_execute, planner_context->getQueryContext()); + subquery_to_execute + = buildSubqueryToReadColumnsFromTableExpression(subquery_to_execute, planner_context->getQueryContext()); - temporary_table_expression_node = executeSubqueryNode(subquery_to_execute, - planner_context->getMutableQueryContext(), - global_in_or_join_node.subquery_depth); + temporary_table_expression_node = executeSubqueryNode( + subquery_to_execute, planner_context->getMutableQueryContext(), global_in_or_join_node.subquery_depth); } replacement_map.emplace(in_function_subquery_node.get(), temporary_table_expression_node); } else { - throw Exception(ErrorCodes::LOGICAL_ERROR, + throw Exception( + ErrorCodes::LOGICAL_ERROR, "Expected global IN or JOIN query node. Actual {}", global_in_or_join_node.query_node->formatASTForErrorMessage()); } diff --git a/src/Storages/extractKeyExpressionList.cpp b/src/Storages/extractKeyExpressionList.cpp index cd03d0d5123..5f9d73bf533 100644 --- a/src/Storages/extractKeyExpressionList.cpp +++ b/src/Storages/extractKeyExpressionList.cpp @@ -16,15 +16,12 @@ namespace DB if (expr_func->arguments) /// Primary key is specified in tuple, extract its arguments. return expr_func->arguments->clone(); - else - return std::make_shared(); - } - else - { - /// Primary key consists of one column. - auto res = std::make_shared(); - res->children.push_back(node); - return res; + return std::make_shared(); } + + /// Primary key consists of one column. + auto res = std::make_shared(); + res->children.push_back(node); + return res; } } diff --git a/src/Storages/transformQueryForExternalDatabase.cpp b/src/Storages/transformQueryForExternalDatabase.cpp index fa98dfe036f..a8e36cb7bbe 100644 --- a/src/Storages/transformQueryForExternalDatabase.cpp +++ b/src/Storages/transformQueryForExternalDatabase.cpp @@ -55,7 +55,7 @@ public: std::string name = node->getColumnName(); if (block_with_constants.has(name)) { - auto result = block_with_constants.getByName(name); + const auto & result = block_with_constants.getByName(name); if (!isColumnConst(*result.column)) return; diff --git a/src/TableFunctions/ITableFunctionDataLake.h b/src/TableFunctions/ITableFunctionDataLake.h index db8287f97bf..9f1dcf95bfa 100644 --- a/src/TableFunctions/ITableFunctionDataLake.h +++ b/src/TableFunctions/ITableFunctionDataLake.h @@ -56,10 +56,8 @@ protected: auto object_storage = TableFunction::getObjectStorage(context, !is_insert_query); return Storage::getTableStructureFromData(object_storage, configuration, std::nullopt, context); } - else - { - return parseColumnsListFromString(configuration->structure, context); - } + + return parseColumnsListFromString(configuration->structure, context); } void parseArguments(const ASTPtr & ast_function, ContextPtr context) override diff --git a/src/TableFunctions/TableFunctionFactory.cpp b/src/TableFunctions/TableFunctionFactory.cpp index f5381576a9a..27e35bf79b3 100644 --- a/src/TableFunctions/TableFunctionFactory.cpp +++ b/src/TableFunctions/TableFunctionFactory.cpp @@ -47,8 +47,7 @@ TableFunctionPtr TableFunctionFactory::get( auto hints = getHints(table_function->name); if (!hints.empty()) throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "Unknown table function {}. Maybe you meant: {}", table_function->name, toString(hints)); - else - throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "Unknown table function {}", table_function->name); + throw Exception(ErrorCodes::UNKNOWN_FUNCTION, "Unknown table function {}", table_function->name); } res->parseArguments(ast_function, context); diff --git a/src/TableFunctions/TableFunctionFile.cpp b/src/TableFunctions/TableFunctionFile.cpp index 9e7352033fc..d2fdf5df83f 100644 --- a/src/TableFunctions/TableFunctionFile.cpp +++ b/src/TableFunctions/TableFunctionFile.cpp @@ -65,8 +65,7 @@ std::optional TableFunctionFile::tryGetFormatFromFirstArgument() { if (fd >= 0) return FormatFactory::instance().tryGetFormatFromFileDescriptor(fd); - else - return FormatFactory::instance().tryGetFormatFromFileName(filename); + return FormatFactory::instance().tryGetFormatFromFileName(filename); } StoragePtr TableFunctionFile::getStorage( diff --git a/src/TableFunctions/TableFunctionNumbers.cpp b/src/TableFunctions/TableFunctionNumbers.cpp index 7d800400374..f2157d192c7 100644 --- a/src/TableFunctions/TableFunctionNumbers.cpp +++ b/src/TableFunctions/TableFunctionNumbers.cpp @@ -88,13 +88,10 @@ StoragePtr TableFunctionNumbers::executeImpl( res->startup(); return res; } - else - { - auto res = std::make_shared( - StorageID(getDatabaseName(), table_name), multithreaded, std::string{"number"}); - res->startup(); - return res; - } + + auto res = std::make_shared(StorageID(getDatabaseName(), table_name), multithreaded, std::string{"number"}); + res->startup(); + return res; } throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "Table function '{}' requires 'limit' or 'offset, limit'.", getName()); } diff --git a/src/TableFunctions/TableFunctionObjectStorage.cpp b/src/TableFunctions/TableFunctionObjectStorage.cpp index 9cebb91044a..8559a4cd668 100644 --- a/src/TableFunctions/TableFunctionObjectStorage.cpp +++ b/src/TableFunctions/TableFunctionObjectStorage.cpp @@ -89,8 +89,7 @@ ColumnsDescription TableFunctionObjectStorage< resolveSchemaAndFormat(columns, configuration->format, storage, configuration, std::nullopt, sample_path, context); return columns; } - else - return parseColumnsListFromString(configuration->structure, context); + return parseColumnsListFromString(configuration->structure, context); } template diff --git a/src/TableFunctions/TableFunctionRemote.cpp b/src/TableFunctions/TableFunctionRemote.cpp index a9cdf1d3540..ed00fd2cef3 100644 --- a/src/TableFunctions/TableFunctionRemote.cpp +++ b/src/TableFunctions/TableFunctionRemote.cpp @@ -183,13 +183,11 @@ void TableFunctionRemote::parseArguments(const ASTPtr & ast_function, ContextPtr { throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "Table name was not found in function arguments. {}", static_cast(help_message)); } - else - { - std::swap(qualified_name.database, qualified_name.table); - args[arg_num] = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context); - qualified_name.table = checkAndGetLiteralArgument(args[arg_num], "table"); - ++arg_num; - } + + std::swap(qualified_name.database, qualified_name.table); + args[arg_num] = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context); + qualified_name.table = checkAndGetLiteralArgument(args[arg_num], "table"); + ++arg_num; } database = std::move(qualified_name.database); diff --git a/src/TableFunctions/TableFunctionZeros.cpp b/src/TableFunctions/TableFunctionZeros.cpp index 5cc02c3e76b..c42281ddbd0 100644 --- a/src/TableFunctions/TableFunctionZeros.cpp +++ b/src/TableFunctions/TableFunctionZeros.cpp @@ -66,13 +66,11 @@ StoragePtr TableFunctionZeros::executeImpl(const ASTPtr & ast_fun res->startup(); return res; } - else - { - /// zero-argument, the same as system.zeros - auto res = std::make_shared(StorageID(getDatabaseName(), table_name), multithreaded); - res->startup(); - return res; - } + + /// zero-argument, the same as system.zeros + auto res = std::make_shared(StorageID(getDatabaseName(), table_name), multithreaded); + res->startup(); + return res; } throw Exception(ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH, "Table function '{}' requires 'limit'.", getName()); } diff --git a/utils/keeper-data-dumper/main.cpp b/utils/keeper-data-dumper/main.cpp index 0291b6e9239..7e8f83d8ea5 100644 --- a/utils/keeper-data-dumper/main.cpp +++ b/utils/keeper-data-dumper/main.cpp @@ -56,12 +56,11 @@ int main(int argc, char *argv[]) std::cerr << "usage: " << argv[0] << " snapshotpath logpath" << std::endl; return 3; } - else - { - Poco::AutoPtr channel(new Poco::ConsoleChannel(std::cerr)); - Poco::Logger::root().setChannel(channel); - Poco::Logger::root().setLevel("trace"); - } + + Poco::AutoPtr channel(new Poco::ConsoleChannel(std::cerr)); + Poco::Logger::root().setChannel(channel); + Poco::Logger::root().setLevel("trace"); + auto logger = getLogger("keeper-dumper"); ResponsesQueue queue(std::numeric_limits::max()); SnapshotsQueue snapshots_queue{1}; diff --git a/utils/zookeeper-dump-tree/main.cpp b/utils/zookeeper-dump-tree/main.cpp index 798eeeaebae..2d997f877b2 100644 --- a/utils/zookeeper-dump-tree/main.cpp +++ b/utils/zookeeper-dump-tree/main.cpp @@ -70,7 +70,7 @@ int main(int argc, char ** argv) { continue; } - else if (Coordination::isHardwareError(e.code)) + if (Coordination::isHardwareError(e.code)) { /// Reinitialize the session and move the node to the end of the queue for later retry. if (!ensure_session()) @@ -78,8 +78,8 @@ int main(int argc, char ** argv) list_futures.emplace_back(it->first, zookeeper->asyncGetChildren(it->first)); continue; } - else - throw; + + throw; } std::cout << it->first << '\t' << response.stat.numChildren << '\t' << response.stat.dataLength;