From 0e325c7a4a46de301922467f7e2ed7b87187e70c Mon Sep 17 00:00:00 2001 From: Ivan Lezhankin Date: Fri, 8 Mar 2019 12:45:34 +0300 Subject: [PATCH 01/11] Replace const typeid_casts with As() method invocations --- dbms/programs/client/Client.cpp | 46 ++++++++------- dbms/programs/copier/ClusterCopier.cpp | 35 ++++++------ .../parseAggregateFunctionParameters.cpp | 8 +-- dbms/src/Compression/CompressionFactory.cpp | 6 +- .../DataTypes/DataTypeAggregateFunction.cpp | 11 ++-- dbms/src/DataTypes/DataTypeDateTime.cpp | 2 +- dbms/src/DataTypes/DataTypeEnum.cpp | 6 +- dbms/src/DataTypes/DataTypeFactory.cpp | 6 +- dbms/src/DataTypes/DataTypeFixedString.cpp | 2 +- dbms/src/DataTypes/DataTypeTuple.cpp | 2 +- dbms/src/DataTypes/DataTypesDecimal.cpp | 6 +- dbms/src/Interpreters/ActionsVisitor.cpp | 13 ++--- dbms/src/Interpreters/Context.cpp | 3 +- .../Interpreters/CrossToInnerJoinVisitor.cpp | 22 ++++---- .../DatabaseAndTableWithAlias.cpp | 2 +- dbms/src/Interpreters/ExpressionAnalyzer.cpp | 16 +++--- .../Interpreters/GlobalSubqueriesVisitor.h | 4 +- dbms/src/Interpreters/IdentifierSemantic.cpp | 4 +- .../Interpreters/InterpreterCreateQuery.cpp | 9 ++- .../Interpreters/InterpreterDescribeQuery.cpp | 8 +-- .../Interpreters/InterpreterExistsQuery.cpp | 4 +- .../Interpreters/InterpreterExplainQuery.cpp | 10 ++-- .../Interpreters/InterpreterInsertQuery.cpp | 2 +- .../Interpreters/InterpreterOptimizeQuery.cpp | 10 ++-- .../Interpreters/InterpreterSelectQuery.cpp | 16 +++--- .../InterpreterSelectWithUnionQuery.cpp | 10 ++-- dbms/src/Interpreters/InterpreterSetQuery.cpp | 12 ++-- .../InterpreterShowTablesQuery.cpp | 14 ++--- dbms/src/Interpreters/InterpreterUseQuery.cpp | 2 +- .../JoinToSubqueryTransformVisitor.cpp | 12 ++-- .../PredicateExpressionsOptimizer.cpp | 2 +- dbms/src/Interpreters/ProcessList.cpp | 6 +- dbms/src/Interpreters/QueryNormalizer.cpp | 3 +- dbms/src/Interpreters/SyntaxAnalyzer.cpp | 26 ++++----- .../TranslateQualifiedNamesVisitor.cpp | 18 +++--- .../evaluateConstantExpression.cpp | 28 +++++----- dbms/src/Interpreters/executeQuery.cpp | 4 +- dbms/src/Interpreters/getClusterName.cpp | 6 +- dbms/src/Interpreters/interpretSubquery.cpp | 6 +- dbms/src/Parsers/ASTFunction.cpp | 6 +- dbms/src/Parsers/ASTIdentifier.cpp | 6 +- dbms/src/Parsers/ASTSelectQuery.cpp | 11 ++-- dbms/src/Parsers/ASTTablesInSelectQuery.cpp | 2 +- dbms/src/Parsers/ExpressionElementParsers.cpp | 3 +- dbms/src/Parsers/IAST.h | 29 ++++++---- dbms/src/Parsers/IAST_fwd.h | 12 ++++ dbms/src/Parsers/ParserAlterQuery.cpp | 4 +- dbms/src/Parsers/ParserCreateQuery.cpp | 8 +-- dbms/src/Parsers/ParserPartition.cpp | 2 +- dbms/src/Parsers/ParserSetQuery.cpp | 2 +- .../parseIdentifierOrStringLiteral.cpp | 2 +- dbms/src/Storages/AlterCommands.cpp | 56 +++++++++---------- dbms/src/Storages/ColumnsDescription.cpp | 2 +- dbms/src/Storages/Kafka/StorageKafka.cpp | 14 ++--- dbms/src/Storages/MergeTree/KeyCondition.cpp | 28 +++++----- dbms/src/Storages/MergeTree/MergeTreeData.cpp | 22 ++++---- .../MergeTree/MergeTreeDataSelectExecutor.cpp | 12 ++-- .../MergeTree/MergeTreeSetSkippingIndex.cpp | 31 +++++----- .../MergeTree/MergeTreeWhereOptimizer.cpp | 14 ++--- .../MergeTree/registerStorageMergeTree.cpp | 14 ++--- dbms/src/Storages/MutationCommands.cpp | 8 +-- dbms/src/Storages/StorageDictionary.cpp | 2 +- dbms/src/Storages/StorageFile.cpp | 2 +- dbms/src/Storages/StorageMaterializedView.cpp | 4 +- dbms/src/Storages/StorageMergeTree.cpp | 2 +- .../Storages/StorageReplicatedMergeTree.cpp | 2 +- .../Storages/System/StorageSystemTables.cpp | 6 +- .../System/StorageSystemZooKeeper.cpp | 22 ++++---- dbms/src/Storages/VirtualColumnUtils.cpp | 14 ++--- .../transformQueryForExternalDatabase.cpp | 6 +- .../src/TableFunctions/ITableFunctionXDBC.cpp | 6 +- .../TableFunctionCatBoostPool.cpp | 2 +- .../src/TableFunctions/TableFunctionMySQL.cpp | 6 +- .../TableFunctions/TableFunctionRemote.cpp | 4 +- 74 files changed, 385 insertions(+), 383 deletions(-) create mode 100644 dbms/src/Parsers/IAST_fwd.h diff --git a/dbms/programs/client/Client.cpp b/dbms/programs/client/Client.cpp index 6b4a0c6eb58..69c9c2a5491 100644 --- a/dbms/programs/client/Client.cpp +++ b/dbms/programs/client/Client.cpp @@ -704,7 +704,7 @@ private: return true; } - ASTInsertQuery * insert = typeid_cast(ast.get()); + const auto * insert = ast->As(); if (insert && insert->data) { @@ -799,14 +799,11 @@ private: written_progress_chars = 0; written_first_block = false; - const ASTSetQuery * set_query = typeid_cast(&*parsed_query); - const ASTUseQuery * use_query = typeid_cast(&*parsed_query); - /// INSERT query for which data transfer is needed (not an INSERT SELECT) is processed separately. - const ASTInsertQuery * insert = typeid_cast(&*parsed_query); - connection->forceConnected(); - if (insert && !insert->select) + /// INSERT query for which data transfer is needed (not an INSERT SELECT) is processed separately. + const auto * insert_query = parsed_query->As(); + if (insert_query && !insert_query->select) processInsertQuery(); else processOrdinaryQuery(); @@ -814,7 +811,7 @@ private: /// Do not change context (current DB, settings) in case of an exception. if (!got_exception) { - if (set_query) + if (const auto * set_query = parsed_query->As()) { /// Save all changes in settings to avoid losing them if the connection is lost. for (const auto & change : set_query->changes) @@ -826,7 +823,7 @@ private: } } - if (use_query) + if (const auto * use_query = parsed_query->As()) { const String & new_database = use_query->database; /// If the client initiates the reconnection, it takes the settings from the config. @@ -858,7 +855,7 @@ private: /// Convert external tables to ExternalTableData and send them using the connection. void sendExternalTables() { - auto * select = typeid_cast(&*parsed_query); + const auto * select = parsed_query->As(); if (!select && !external_tables.empty()) throw Exception("External tables could be sent only with select query", ErrorCodes::BAD_ARGUMENTS); @@ -883,12 +880,12 @@ private: void processInsertQuery() { /// Send part of query without data, because data will be sent separately. - const ASTInsertQuery & parsed_insert_query = typeid_cast(*parsed_query); - String query_without_data = parsed_insert_query.data - ? query.substr(0, parsed_insert_query.data - query.data()) + const auto * insert_query = parsed_query->As(); + String query_without_data = insert_query->data + ? query.substr(0, insert_query->data - query.data()) : query; - if (!parsed_insert_query.data && (is_interactive || (stdin_is_not_tty && std_in.eof()))) + if (!insert_query->data && (is_interactive || (stdin_is_not_tty && std_in.eof()))) throw Exception("No data to insert", ErrorCodes::NO_DATA_TO_INSERT); connection->sendQuery(query_without_data, query_id, QueryProcessingStage::Complete, &context.getSettingsRef(), nullptr, true); @@ -940,14 +937,14 @@ private: void sendData(Block & sample, const ColumnsDescription & columns_description) { /// If INSERT data must be sent. - const ASTInsertQuery * parsed_insert_query = typeid_cast(&*parsed_query); - if (!parsed_insert_query) + const auto * insert_query = parsed_query->As(); + if (!insert_query) return; - if (parsed_insert_query->data) + if (insert_query->data) { /// Send data contained in the query. - ReadBufferFromMemory data_in(parsed_insert_query->data, parsed_insert_query->end - parsed_insert_query->data); + ReadBufferFromMemory data_in(insert_query->data, insert_query->end - insert_query->data); sendDataFrom(data_in, sample, columns_description); } else if (!is_interactive) @@ -965,7 +962,7 @@ private: String current_format = insert_format; /// Data format can be specified in the INSERT query. - if (ASTInsertQuery * insert = typeid_cast(&*parsed_query)) + if (const auto * insert = parsed_query->As()) { if (!insert->format.empty()) current_format = insert->format; @@ -1233,10 +1230,11 @@ private: /// The query can specify output format or output file. if (ASTQueryWithOutput * query_with_output = dynamic_cast(&*parsed_query)) { - if (query_with_output->out_file != nullptr) + if (query_with_output->out_file) { - const auto & out_file_node = typeid_cast(*query_with_output->out_file); - const auto & out_file = out_file_node.value.safeGet(); + const auto * out_file_node = query_with_output->out_file->As(); + const auto & out_file = out_file_node->value.safeGet(); + out_file_buf.emplace(out_file, DBMS_DEFAULT_BUFFER_SIZE, O_WRONLY | O_EXCL | O_CREAT); out_buf = &*out_file_buf; @@ -1248,8 +1246,8 @@ private: { if (has_vertical_output_suffix) throw Exception("Output format already specified", ErrorCodes::CLIENT_OUTPUT_FORMAT_SPECIFIED); - const auto & id = typeid_cast(*query_with_output->format); - current_format = id.name; + const auto * id = query_with_output->format->As(); + current_format = id->name; } if (query_with_output->settings_ast) { diff --git a/dbms/programs/copier/ClusterCopier.cpp b/dbms/programs/copier/ClusterCopier.cpp index 588c9984f58..4fb037f01b4 100644 --- a/dbms/programs/copier/ClusterCopier.cpp +++ b/dbms/programs/copier/ClusterCopier.cpp @@ -483,37 +483,37 @@ String DB::TaskShard::getHostNameExample() const static bool isExtendedDefinitionStorage(const ASTPtr & storage_ast) { - const ASTStorage & storage = typeid_cast(*storage_ast); - return storage.partition_by || storage.order_by || storage.sample_by; + const auto * storage = storage_ast->As(); + return storage->partition_by || storage->order_by || storage->sample_by; } static ASTPtr extractPartitionKey(const ASTPtr & storage_ast) { String storage_str = queryToString(storage_ast); - const ASTStorage & storage = typeid_cast(*storage_ast); - const ASTFunction & engine = typeid_cast(*storage.engine); + const auto * storage = storage_ast->As(); + const auto * engine = storage->engine->As(); - if (!endsWith(engine.name, "MergeTree")) + if (!endsWith(engine->name, "MergeTree")) { throw Exception("Unsupported engine was specified in " + storage_str + ", only *MergeTree engines are supported", ErrorCodes::BAD_ARGUMENTS); } - ASTPtr arguments_ast = engine.arguments->clone(); - ASTs & arguments = typeid_cast(*arguments_ast).children; + ASTPtr arguments_ast = engine->arguments->clone(); + ASTs & arguments = arguments_ast->As()->children; // FIXME: what' the point of casting? if (isExtendedDefinitionStorage(storage_ast)) { - if (storage.partition_by) - return storage.partition_by->clone(); + if (storage->partition_by) + return storage->partition_by->clone(); static const char * all = "all"; return std::make_shared(Field(all, strlen(all))); } else { - bool is_replicated = startsWith(engine.name, "Replicated"); + bool is_replicated = startsWith(engine->name, "Replicated"); size_t min_args = is_replicated ? 3 : 1; if (arguments.size() < min_args) @@ -1179,16 +1179,16 @@ protected: /// Removes MATERIALIZED and ALIAS columns from create table query static ASTPtr removeAliasColumnsFromCreateQuery(const ASTPtr & query_ast) { - const ASTs & column_asts = typeid_cast(*query_ast).columns_list->columns->children; + const ASTs & column_asts = query_ast->As()->columns_list->columns->children; auto new_columns = std::make_shared(); for (const ASTPtr & column_ast : column_asts) { - const ASTColumnDeclaration & column = typeid_cast(*column_ast); + const auto * column = column_ast->As(); - if (!column.default_specifier.empty()) + if (!column->default_specifier.empty()) { - ColumnDefaultKind kind = columnDefaultKindFromString(column.default_specifier); + ColumnDefaultKind kind = columnDefaultKindFromString(column->default_specifier); if (kind == ColumnDefaultKind::Materialized || kind == ColumnDefaultKind::Alias) continue; } @@ -1197,14 +1197,13 @@ protected: } ASTPtr new_query_ast = query_ast->clone(); - ASTCreateQuery & new_query = typeid_cast(*new_query_ast); + auto * new_query = new_query_ast->As(); auto new_columns_list = std::make_shared(); new_columns_list->set(new_columns_list->columns, new_columns); - new_columns_list->set( - new_columns_list->indices, typeid_cast(*query_ast).columns_list->indices->clone()); + new_columns_list->set(new_columns_list->indices, query_ast->As()->columns_list->indices->clone()); - new_query.replace(new_query.columns_list, new_columns_list); + new_query->replace(new_query->columns_list, new_columns_list); return new_query_ast; } diff --git a/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp b/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp index 5e5738592f7..21185f5f542 100644 --- a/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp +++ b/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp @@ -15,7 +15,7 @@ namespace ErrorCodes Array getAggregateFunctionParametersArray(const ASTPtr & expression_list, const std::string & error_context) { - const ASTs & parameters = typeid_cast(*expression_list).children; + const ASTs & parameters = expression_list->As()->children; if (parameters.empty()) throw Exception("Parameters list to aggregate functions cannot be empty", ErrorCodes::BAD_ARGUMENTS); @@ -23,14 +23,14 @@ Array getAggregateFunctionParametersArray(const ASTPtr & expression_list, const for (size_t i = 0; i < parameters.size(); ++i) { - const ASTLiteral * lit = typeid_cast(parameters[i].get()); - if (!lit) + const auto * literal = parameters[i]->As(); + if (!literal) { throw Exception("Parameters to aggregate functions must be literals" + (error_context.empty() ? "" : " (in " + error_context +")"), ErrorCodes::PARAMETERS_TO_AGGREGATE_FUNCTIONS_MUST_BE_LITERALS); } - params_row[i] = lit->value; + params_row[i] = literal->value; } return params_row; diff --git a/dbms/src/Compression/CompressionFactory.cpp b/dbms/src/Compression/CompressionFactory.cpp index 7f7dbac21df..aad274374e9 100644 --- a/dbms/src/Compression/CompressionFactory.cpp +++ b/dbms/src/Compression/CompressionFactory.cpp @@ -57,15 +57,15 @@ CompressionCodecPtr CompressionCodecFactory::get(const std::vector(ast.get())) + if (const auto * func = ast->As()) { Codecs codecs; codecs.reserve(func->arguments->children.size()); for (const auto & inner_codec_ast : func->arguments->children) { - if (const auto * family_name = typeid_cast(inner_codec_ast.get())) + if (const auto * family_name = inner_codec_ast->As()) codecs.emplace_back(getImpl(family_name->name, {}, column_type)); - else if (const auto * ast_func = typeid_cast(inner_codec_ast.get())) + else if (const auto * ast_func = inner_codec_ast->As()) codecs.emplace_back(getImpl(ast_func->name, ast_func->arguments, column_type)); else throw Exception("Unexpected AST element for compression codec", ErrorCodes::UNEXPECTED_AST_STRUCTURE); diff --git a/dbms/src/DataTypes/DataTypeAggregateFunction.cpp b/dbms/src/DataTypes/DataTypeAggregateFunction.cpp index 25ed8836538..7441f3205aa 100644 --- a/dbms/src/DataTypes/DataTypeAggregateFunction.cpp +++ b/dbms/src/DataTypes/DataTypeAggregateFunction.cpp @@ -340,23 +340,23 @@ static DataTypePtr create(const ASTPtr & arguments) throw Exception("Data type AggregateFunction requires parameters: " "name of aggregate function and list of data types for arguments", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - if (const ASTFunction * parametric = typeid_cast(arguments->children[0].get())) + if (const auto * parametric = arguments->children[0]->As()) { if (parametric->parameters) throw Exception("Unexpected level of parameters to aggregate function", ErrorCodes::SYNTAX_ERROR); function_name = parametric->name; - const ASTs & parameters = typeid_cast(*parametric->arguments).children; + const ASTs & parameters = parametric->arguments->As()->children; params_row.resize(parameters.size()); for (size_t i = 0; i < parameters.size(); ++i) { - const ASTLiteral * lit = typeid_cast(parameters[i].get()); - if (!lit) + const auto * literal = parameters[i]->As(); + if (!literal) throw Exception("Parameters to aggregate functions must be literals", ErrorCodes::PARAMETERS_TO_AGGREGATE_FUNCTIONS_MUST_BE_LITERALS); - params_row[i] = lit->value; + params_row[i] = literal->value; } } else if (auto opt_name = getIdentifierName(arguments->children[0])) @@ -389,4 +389,3 @@ void registerDataTypeAggregateFunction(DataTypeFactory & factory) } - diff --git a/dbms/src/DataTypes/DataTypeDateTime.cpp b/dbms/src/DataTypes/DataTypeDateTime.cpp index 25b2d966e6b..08864cc9693 100644 --- a/dbms/src/DataTypes/DataTypeDateTime.cpp +++ b/dbms/src/DataTypes/DataTypeDateTime.cpp @@ -186,7 +186,7 @@ static DataTypePtr create(const ASTPtr & arguments) if (arguments->children.size() != 1) throw Exception("DateTime data type can optionally have only one argument - time zone name", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - const ASTLiteral * arg = typeid_cast(arguments->children[0].get()); + const auto * arg = arguments->children[0]->As(); if (!arg || arg->value.getType() != Field::Types::String) throw Exception("Parameter for DateTime data type must be string literal", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); diff --git a/dbms/src/DataTypes/DataTypeEnum.cpp b/dbms/src/DataTypes/DataTypeEnum.cpp index bd93105a288..b59922ab1af 100644 --- a/dbms/src/DataTypes/DataTypeEnum.cpp +++ b/dbms/src/DataTypes/DataTypeEnum.cpp @@ -357,7 +357,7 @@ static DataTypePtr create(const ASTPtr & arguments) /// Children must be functions 'equals' with string literal as left argument and numeric literal as right argument. for (const ASTPtr & child : arguments->children) { - const ASTFunction * func = typeid_cast(child.get()); + const auto * func = child->As(); if (!func || func->name != "equals" || func->parameters @@ -366,8 +366,8 @@ static DataTypePtr create(const ASTPtr & arguments) throw Exception("Elements of Enum data type must be of form: 'name' = number, where name is string literal and number is an integer", ErrorCodes::UNEXPECTED_AST_STRUCTURE); - const ASTLiteral * name_literal = typeid_cast(func->arguments->children[0].get()); - const ASTLiteral * value_literal = typeid_cast(func->arguments->children[1].get()); + const auto * name_literal = func->arguments->children[0]->As(); + const auto * value_literal = func->arguments->children[1]->As(); if (!name_literal || !value_literal diff --git a/dbms/src/DataTypes/DataTypeFactory.cpp b/dbms/src/DataTypes/DataTypeFactory.cpp index 85df6bee260..1c5aeeddf20 100644 --- a/dbms/src/DataTypes/DataTypeFactory.cpp +++ b/dbms/src/DataTypes/DataTypeFactory.cpp @@ -32,19 +32,19 @@ DataTypePtr DataTypeFactory::get(const String & full_name) const DataTypePtr DataTypeFactory::get(const ASTPtr & ast) const { - if (const ASTFunction * func = typeid_cast(ast.get())) + if (const auto * func = ast->As()) { if (func->parameters) throw Exception("Data type cannot have multiple parenthesed parameters.", ErrorCodes::ILLEGAL_SYNTAX_FOR_DATA_TYPE); return get(func->name, func->arguments); } - if (const ASTIdentifier * ident = typeid_cast(ast.get())) + if (const auto * ident = ast->As()) { return get(ident->name, {}); } - if (const ASTLiteral * lit = typeid_cast(ast.get())) + if (const auto * lit = ast->As()) { if (lit->value.isNull()) return get("Null", {}); diff --git a/dbms/src/DataTypes/DataTypeFixedString.cpp b/dbms/src/DataTypes/DataTypeFixedString.cpp index 356c69351ef..a5a35f81742 100644 --- a/dbms/src/DataTypes/DataTypeFixedString.cpp +++ b/dbms/src/DataTypes/DataTypeFixedString.cpp @@ -273,7 +273,7 @@ static DataTypePtr create(const ASTPtr & arguments) if (!arguments || arguments->children.size() != 1) throw Exception("FixedString data type family must have exactly one argument - size in bytes", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - const ASTLiteral * argument = typeid_cast(arguments->children[0].get()); + const auto * argument = arguments->children[0]->As(); if (!argument || argument->value.getType() != Field::Types::UInt64 || argument->value.get() == 0) throw Exception("FixedString data type family must have a number (positive integer) as its argument", ErrorCodes::UNEXPECTED_AST_STRUCTURE); diff --git a/dbms/src/DataTypes/DataTypeTuple.cpp b/dbms/src/DataTypes/DataTypeTuple.cpp index a799662429f..e4f2cba1e44 100644 --- a/dbms/src/DataTypes/DataTypeTuple.cpp +++ b/dbms/src/DataTypes/DataTypeTuple.cpp @@ -531,7 +531,7 @@ static DataTypePtr create(const ASTPtr & arguments) for (const ASTPtr & child : arguments->children) { - if (const ASTNameTypePair * name_and_type_pair = typeid_cast(child.get())) + if (const auto * name_and_type_pair = child->As()) { nested_types.emplace_back(DataTypeFactory::instance().get(name_and_type_pair->type)); names.emplace_back(name_and_type_pair->name); diff --git a/dbms/src/DataTypes/DataTypesDecimal.cpp b/dbms/src/DataTypes/DataTypesDecimal.cpp index a89196b0f0a..509f613defb 100644 --- a/dbms/src/DataTypes/DataTypesDecimal.cpp +++ b/dbms/src/DataTypes/DataTypesDecimal.cpp @@ -208,8 +208,8 @@ static DataTypePtr create(const ASTPtr & arguments) throw Exception("Decimal data type family must have exactly two arguments: precision and scale", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - const ASTLiteral * precision = typeid_cast(arguments->children[0].get()); - const ASTLiteral * scale = typeid_cast(arguments->children[1].get()); + const auto * precision = arguments->children[0]->As(); + const auto * scale = arguments->children[1]->As(); if (!precision || precision->value.getType() != Field::Types::UInt64 || !scale || !(scale->value.getType() == Field::Types::Int64 || scale->value.getType() == Field::Types::UInt64)) @@ -228,7 +228,7 @@ static DataTypePtr createExect(const ASTPtr & arguments) throw Exception("Decimal data type family must have exactly two arguments: precision and scale", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - const ASTLiteral * scale_arg = typeid_cast(arguments->children[0].get()); + const auto * scale_arg = arguments->children[0]->As(); if (!scale_arg || !(scale_arg->value.getType() == Field::Types::Int64 || scale_arg->value.getType() == Field::Types::UInt64)) throw Exception("Decimal data type family must have a two numbers as its arguments", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); diff --git a/dbms/src/Interpreters/ActionsVisitor.cpp b/dbms/src/Interpreters/ActionsVisitor.cpp index 0dba4f6a163..a59fbc1c722 100644 --- a/dbms/src/Interpreters/ActionsVisitor.cpp +++ b/dbms/src/Interpreters/ActionsVisitor.cpp @@ -84,11 +84,11 @@ SetPtr makeExplicitSet( auto getTupleTypeFromAst = [&context](const ASTPtr & tuple_ast) -> DataTypePtr { - auto ast_function = typeid_cast(tuple_ast.get()); - if (ast_function && ast_function->name == "tuple" && !ast_function->arguments->children.empty()) + const auto * func = tuple_ast->As(); + if (func && func->name == "tuple" && !func->arguments->children.empty()) { /// Won't parse all values of outer tuple. - auto element = ast_function->arguments->children.at(0); + auto element = func->arguments->children.at(0); std::pair value_raw = evaluateConstantExpression(element, context); return std::make_shared(DataTypes({value_raw.second})); } @@ -533,8 +533,7 @@ void ActionsVisitor::visit(const ASTPtr & ast) for (auto & child : ast->children) { /// Do not go to FROM, JOIN, UNION. - if (!typeid_cast(child.get()) - && !typeid_cast(child.get())) + if (!child->As() && !child->As()) visit(child); } } @@ -550,8 +549,8 @@ SetPtr ActionsVisitor::makeSet(const ASTFunction * node, const Block & sample_bl const ASTPtr & arg = args.children.at(1); /// If the subquery or table name for SELECT. - const ASTIdentifier * identifier = typeid_cast(arg.get()); - if (typeid_cast(arg.get()) || identifier) + const auto * identifier = arg->As(); + if (arg->As() || identifier) { auto set_key = PreparedSetKey::forSubquery(*arg); if (prepared_sets.count(set_key)) diff --git a/dbms/src/Interpreters/Context.cpp b/dbms/src/Interpreters/Context.cpp index b7613116f2d..03da9e0d2a5 100644 --- a/dbms/src/Interpreters/Context.cpp +++ b/dbms/src/Interpreters/Context.cpp @@ -892,8 +892,7 @@ StoragePtr Context::executeTableFunction(const ASTPtr & table_expression) if (!res) { - TableFunctionPtr table_function_ptr = TableFunctionFactory::instance().get( - typeid_cast(table_expression.get())->name, *this); + TableFunctionPtr table_function_ptr = TableFunctionFactory::instance().get(table_expression->As()->name, *this); /// Run it and remember the result res = table_function_ptr->execute(table_expression, *this); diff --git a/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp b/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp index 8c74ddf699a..ad449899438 100644 --- a/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp +++ b/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp @@ -41,7 +41,7 @@ public: for (auto & child : node.arguments->children) { - if (auto func = typeid_cast(child.get())) + if (const auto * func = child->As()) { if (func->name == "and") flat_ands = false; @@ -92,8 +92,8 @@ private: if (node.arguments->children.size() != 2) return false; - auto left = typeid_cast(node.arguments->children[0].get()); - auto right = typeid_cast(node.arguments->children[1].get()); + const auto * left = node.arguments->children[0]->As(); + const auto * right = node.arguments->children[1]->As(); if (!left || !right) return false; @@ -146,7 +146,7 @@ static ASTPtr getCrossJoin(ASTSelectQuery & select, std::vector(select.tables.get()); + const auto * tables = select.tables->As(); if (!tables) return {}; @@ -154,12 +154,12 @@ static ASTPtr getCrossJoin(ASTSelectQuery & select, std::vector(tables->children[0].get()); - auto right = typeid_cast(tables->children[1].get()); + const auto * left = tables->children[0]->As(); + const auto * right = tables->children[1]->As(); if (!left || !right || !right->table_join) return {}; - if (auto join = typeid_cast(right->table_join.get())) + if (const auto * join = right->table_join->As()) { if (join->kind == ASTTableJoin::Kind::Cross || join->kind == ASTTableJoin::Kind::Comma) @@ -167,12 +167,12 @@ static ASTPtr getCrossJoin(ASTSelectQuery & select, std::vectorchildren.empty()) throw Exception("Logical error: CROSS JOIN has expressions", ErrorCodes::LOGICAL_ERROR); - auto & left_expr = typeid_cast(*left->table_expression); - auto & right_expr = typeid_cast(*right->table_expression); + const auto * left_expr = left->table_expression->As(); + const auto * right_expr = right->table_expression->As(); table_names.reserve(2); - if (extractTableName(left_expr, table_names) && - extractTableName(right_expr, table_names)) + if (extractTableName(*left_expr, table_names) && + extractTableName(*right_expr, table_names)) return right->table_join; } } diff --git a/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp b/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp index 52b05fc5933..8ff1d66ff4a 100644 --- a/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp +++ b/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp @@ -27,7 +27,7 @@ DatabaseAndTableWithAlias::DatabaseAndTableWithAlias(const ASTIdentifier & ident DatabaseAndTableWithAlias::DatabaseAndTableWithAlias(const ASTPtr & node, const String & current_database) { - const auto * identifier = typeid_cast(node.get()); + const auto * identifier = node->As(); if (!identifier) throw Exception("Logical error: identifier expected", ErrorCodes::LOGICAL_ERROR); diff --git a/dbms/src/Interpreters/ExpressionAnalyzer.cpp b/dbms/src/Interpreters/ExpressionAnalyzer.cpp index 4a2e62fe1ec..6c9089eb389 100644 --- a/dbms/src/Interpreters/ExpressionAnalyzer.cpp +++ b/dbms/src/Interpreters/ExpressionAnalyzer.cpp @@ -292,14 +292,14 @@ void ExpressionAnalyzer::makeSetsForIndexImpl(const ASTPtr & node) continue; /// Don't descend into lambda functions - const ASTFunction * func = typeid_cast(child.get()); + const auto * func = child->As(); if (func && func->name == "lambda") continue; makeSetsForIndexImpl(child); } - const ASTFunction * func = typeid_cast(node.get()); + const auto * func = node->As(); if (func && functionIsInOperator(func->name)) { const IAST & args = *func->arguments; @@ -379,7 +379,7 @@ void ExpressionAnalyzer::getAggregates(const ASTPtr & ast, ExpressionActionsPtr return; } - const ASTFunction * node = typeid_cast(ast.get()); + const auto * node = ast->As(); if (node && AggregateFunctionFactory::instance().isAggregateFunctionName(node->name)) { has_aggregation = true; @@ -414,8 +414,7 @@ void ExpressionAnalyzer::getAggregates(const ASTPtr & ast, ExpressionActionsPtr else { for (const auto & child : ast->children) - if (!typeid_cast(child.get()) - && !typeid_cast(child.get())) + if (!child->As() && !child->As()) getAggregates(child, actions); } } @@ -423,15 +422,14 @@ void ExpressionAnalyzer::getAggregates(const ASTPtr & ast, ExpressionActionsPtr void ExpressionAnalyzer::assertNoAggregates(const ASTPtr & ast, const char * description) { - const ASTFunction * node = typeid_cast(ast.get()); + const auto * node = ast->As(); if (node && AggregateFunctionFactory::instance().isAggregateFunctionName(node->name)) throw Exception("Aggregate function " + node->getColumnName() + " is found " + String(description) + " in query", ErrorCodes::ILLEGAL_AGGREGATION); for (const auto & child : ast->children) - if (!typeid_cast(child.get()) - && !typeid_cast(child.get())) + if (!child->As() && !child->As()) assertNoAggregates(child, description); } @@ -883,7 +881,7 @@ ExpressionActionsPtr ExpressionAnalyzer::getActions(bool add_aliases, bool proje ASTs asts; - if (auto node = typeid_cast(query.get())) + if (const auto * node = query->As()) asts = node->children; else asts = ASTs(1, query); diff --git a/dbms/src/Interpreters/GlobalSubqueriesVisitor.h b/dbms/src/Interpreters/GlobalSubqueriesVisitor.h index 644ed7fe5d2..a394a7cf567 100644 --- a/dbms/src/Interpreters/GlobalSubqueriesVisitor.h +++ b/dbms/src/Interpreters/GlobalSubqueriesVisitor.h @@ -61,7 +61,7 @@ public: table_name = subquery_or_table_name_or_table_expression; subquery_or_table_name = table_name; } - else if (auto ast_table_expr = typeid_cast(subquery_or_table_name_or_table_expression.get())) + else if (const auto * ast_table_expr = subquery_or_table_name_or_table_expression->As()) { if (ast_table_expr->database_and_table_name) { @@ -74,7 +74,7 @@ public: subquery_or_table_name = subquery; } } - else if (typeid_cast(subquery_or_table_name_or_table_expression.get())) + else if (subquery_or_table_name_or_table_expression->As()) { subquery = subquery_or_table_name_or_table_expression; subquery_or_table_name = subquery; diff --git a/dbms/src/Interpreters/IdentifierSemantic.cpp b/dbms/src/Interpreters/IdentifierSemantic.cpp index e4ea91534af..35597d1b915 100644 --- a/dbms/src/Interpreters/IdentifierSemantic.cpp +++ b/dbms/src/Interpreters/IdentifierSemantic.cpp @@ -15,7 +15,7 @@ std::optional IdentifierSemantic::getColumnName(const ASTIdentifier & no std::optional IdentifierSemantic::getColumnName(const ASTPtr & ast) { if (ast) - if (auto id = typeid_cast(ast.get())) + if (const auto * id = ast->As()) if (!id->semantic->special) return id->name; return {}; @@ -31,7 +31,7 @@ std::optional IdentifierSemantic::getTableName(const ASTIdentifier & nod std::optional IdentifierSemantic::getTableName(const ASTPtr & ast) { if (ast) - if (auto id = typeid_cast(ast.get())) + if (const auto * id = ast->As()) if (id->semantic->special) return id->name; return {}; diff --git a/dbms/src/Interpreters/InterpreterCreateQuery.cpp b/dbms/src/Interpreters/InterpreterCreateQuery.cpp index 708bd616828..f056d4204b5 100644 --- a/dbms/src/Interpreters/InterpreterCreateQuery.cpp +++ b/dbms/src/Interpreters/InterpreterCreateQuery.cpp @@ -525,14 +525,14 @@ void InterpreterCreateQuery::setEngine(ASTCreateQuery & create) const String as_table_name = create.as_table; ASTPtr as_create_ptr = context.getCreateTableQuery(as_database_name, as_table_name); - const auto & as_create = typeid_cast(*as_create_ptr); + const auto * as_create = as_create_ptr->As(); - if (as_create.is_view) + if (as_create->is_view) throw Exception( "Cannot CREATE a table AS " + as_database_name + "." + as_table_name + ", it is a View", ErrorCodes::INCORRECT_QUERY); - create.set(create.storage, as_create.storage->ptr()); + create.set(create.storage, as_create->storage->ptr()); } } @@ -565,8 +565,7 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) { // Table SQL definition is available even if the table is detached auto query = context.getCreateTableQuery(database_name, table_name); - auto & as_create = typeid_cast(*query); - create = as_create; // Copy the saved create query, but use ATTACH instead of CREATE + create = *query->As(); // Copy the saved create query, but use ATTACH instead of CREATE create.attach = true; } diff --git a/dbms/src/Interpreters/InterpreterDescribeQuery.cpp b/dbms/src/Interpreters/InterpreterDescribeQuery.cpp index 19cb167168e..dda5f6753e6 100644 --- a/dbms/src/Interpreters/InterpreterDescribeQuery.cpp +++ b/dbms/src/Interpreters/InterpreterDescribeQuery.cpp @@ -58,7 +58,7 @@ Block InterpreterDescribeQuery::getSampleBlock() BlockInputStreamPtr InterpreterDescribeQuery::executeImpl() { - const ASTDescribeQuery & ast = typeid_cast(*query_ptr); + const auto * ast = query_ptr->As(); NamesAndTypesList columns; ColumnDefaults column_defaults; @@ -66,7 +66,7 @@ BlockInputStreamPtr InterpreterDescribeQuery::executeImpl() ColumnCodecs column_codecs; StoragePtr table; - auto table_expression = typeid_cast(ast.table_expression.get()); + const auto * table_expression = ast->table_expression->As(); if (table_expression->subquery) { @@ -76,7 +76,7 @@ BlockInputStreamPtr InterpreterDescribeQuery::executeImpl() { if (table_expression->table_function) { - auto table_function = typeid_cast(table_expression->table_function.get()); + const auto * table_function = table_expression->table_function->As(); /// Get the table function TableFunctionPtr table_function_ptr = TableFunctionFactory::instance().get(table_function->name, context); /// Run it and remember the result @@ -84,7 +84,7 @@ BlockInputStreamPtr InterpreterDescribeQuery::executeImpl() } else { - auto identifier = typeid_cast(table_expression->database_and_table_name.get()); + const auto * identifier = table_expression->database_and_table_name->As(); String database_name; String table_name; diff --git a/dbms/src/Interpreters/InterpreterExistsQuery.cpp b/dbms/src/Interpreters/InterpreterExistsQuery.cpp index d718479e669..145577b292b 100644 --- a/dbms/src/Interpreters/InterpreterExistsQuery.cpp +++ b/dbms/src/Interpreters/InterpreterExistsQuery.cpp @@ -32,8 +32,8 @@ Block InterpreterExistsQuery::getSampleBlock() BlockInputStreamPtr InterpreterExistsQuery::executeImpl() { - const ASTExistsQuery & ast = typeid_cast(*query_ptr); - bool res = ast.temporary ? context.isExternalTableExist(ast.table) : context.isTableExist(ast.database, ast.table); + const auto * ast = query_ptr->As(); + bool res = ast->temporary ? context.isExternalTableExist(ast->table) : context.isTableExist(ast->database, ast->table); return std::make_shared(Block{{ ColumnUInt8::create(1, res), diff --git a/dbms/src/Interpreters/InterpreterExplainQuery.cpp b/dbms/src/Interpreters/InterpreterExplainQuery.cpp index be7a592ecb9..b939c8392af 100644 --- a/dbms/src/Interpreters/InterpreterExplainQuery.cpp +++ b/dbms/src/Interpreters/InterpreterExplainQuery.cpp @@ -39,19 +39,19 @@ Block InterpreterExplainQuery::getSampleBlock() BlockInputStreamPtr InterpreterExplainQuery::executeImpl() { - const ASTExplainQuery & ast = typeid_cast(*query); + const auto * ast = query->As(); Block sample_block = getSampleBlock(); MutableColumns res_columns = sample_block.cloneEmptyColumns(); std::stringstream ss; - if (ast.getKind() == ASTExplainQuery::ParsedAST) + if (ast->getKind() == ASTExplainQuery::ParsedAST) { - dumpAST(ast, ss); + dumpAST(*ast, ss); } - else if (ast.getKind() == ASTExplainQuery::AnalyzedSyntax) + else if (ast->getKind() == ASTExplainQuery::AnalyzedSyntax) { - InterpreterSelectWithUnionQuery interpreter(ast.children.at(0), context, {}, QueryProcessingStage::FetchColumns, 0, true, true); + InterpreterSelectWithUnionQuery interpreter(ast->children.at(0), context, {}, QueryProcessingStage::FetchColumns, 0, true, true); interpreter.getQuery()->format(IAST::FormatSettings(ss, false)); } diff --git a/dbms/src/Interpreters/InterpreterInsertQuery.cpp b/dbms/src/Interpreters/InterpreterInsertQuery.cpp index 00cf8e925cd..71f12212172 100644 --- a/dbms/src/Interpreters/InterpreterInsertQuery.cpp +++ b/dbms/src/Interpreters/InterpreterInsertQuery.cpp @@ -46,7 +46,7 @@ StoragePtr InterpreterInsertQuery::getTable(const ASTInsertQuery & query) { if (query.table_function) { - auto table_function = typeid_cast(query.table_function.get()); + const auto * table_function = query.table_function->As(); const auto & factory = TableFunctionFactory::instance(); return factory.get(table_function->name, context)->execute(query.table_function, context); } diff --git a/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp b/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp index 78978794386..1fc6b047197 100644 --- a/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp +++ b/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp @@ -17,14 +17,14 @@ namespace ErrorCodes BlockIO InterpreterOptimizeQuery::execute() { - const ASTOptimizeQuery & ast = typeid_cast(*query_ptr); + const auto * ast = query_ptr->As(); - if (!ast.cluster.empty()) - return executeDDLQueryOnCluster(query_ptr, context, {ast.database}); + if (!ast->cluster.empty()) + return executeDDLQueryOnCluster(query_ptr, context, {ast->database}); - StoragePtr table = context.getTable(ast.database, ast.table); + StoragePtr table = context.getTable(ast->database, ast->table); auto table_lock = table->lockStructure(true, context.getCurrentQueryId()); - table->optimize(query_ptr, ast.partition, ast.final, ast.deduplicate, context); + table->optimize(query_ptr, ast->partition, ast->final, ast->deduplicate, context); return {}; } diff --git a/dbms/src/Interpreters/InterpreterSelectQuery.cpp b/dbms/src/Interpreters/InterpreterSelectQuery.cpp index 2b07ee9c881..8fca2827fd9 100644 --- a/dbms/src/Interpreters/InterpreterSelectQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSelectQuery.cpp @@ -163,8 +163,8 @@ InterpreterSelectQuery::InterpreterSelectQuery( bool is_subquery = false; if (table_expression) { - is_table_func = typeid_cast(table_expression.get()); - is_subquery = typeid_cast(table_expression.get()); + is_table_func = table_expression->As(); + is_subquery = table_expression->As(); } if (input) @@ -1265,13 +1265,13 @@ static SortDescription getSortDescription(ASTSelectQuery & query) for (const auto & elem : query.order_expression_list->children) { String name = elem->children.front()->getColumnName(); - const ASTOrderByElement & order_by_elem = typeid_cast(*elem); + const auto * order_by_elem = elem->As(); std::shared_ptr collator; - if (order_by_elem.collation) - collator = std::make_shared(typeid_cast(*order_by_elem.collation).value.get()); + if (order_by_elem->collation) + collator = std::make_shared(order_by_elem->collation->As()->value.get()); - order_descr.emplace_back(name, order_by_elem.direction, order_by_elem.nulls_direction, collator); + order_descr.emplace_back(name, order_by_elem->direction, order_by_elem->nulls_direction, collator); } return order_descr; @@ -1430,10 +1430,10 @@ bool hasWithTotalsInAnySubqueryInFromClause(const ASTSelectQuery & query) if (auto query_table = extractTableExpression(query, 0)) { - if (auto ast_union = typeid_cast(query_table.get())) + if (const auto * ast_union = query_table->As()) { for (const auto & elem : ast_union->list_of_selects->children) - if (hasWithTotalsInAnySubqueryInFromClause(typeid_cast(*elem))) + if (hasWithTotalsInAnySubqueryInFromClause(*elem->As())) return true; } } diff --git a/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp b/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp index 1dc5419223e..6add9f205a0 100644 --- a/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp @@ -36,9 +36,9 @@ InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery( to_stage(to_stage_), subquery_depth(subquery_depth_) { - const ASTSelectWithUnionQuery & ast = typeid_cast(*query_ptr); + const auto * ast = query_ptr->As(); - size_t num_selects = ast.list_of_selects->children.size(); + size_t num_selects = ast->list_of_selects->children.size(); if (!num_selects) throw Exception("Logical error: no children in ASTSelectWithUnionQuery", ErrorCodes::LOGICAL_ERROR); @@ -57,7 +57,7 @@ InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery( /// We use it to determine positions of 'required_result_column_names' in SELECT clause. Block full_result_header = InterpreterSelectQuery( - ast.list_of_selects->children.at(0), context, Names(), to_stage, subquery_depth, true).getSampleBlock(); + ast->list_of_selects->children.at(0), context, Names(), to_stage, subquery_depth, true).getSampleBlock(); std::vector positions_of_required_result_columns(required_result_column_names.size()); for (size_t required_result_num = 0, size = required_result_column_names.size(); required_result_num < size; ++required_result_num) @@ -66,7 +66,7 @@ InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery( for (size_t query_num = 1; query_num < num_selects; ++query_num) { Block full_result_header_for_current_select = InterpreterSelectQuery( - ast.list_of_selects->children.at(query_num), context, Names(), to_stage, subquery_depth, true).getSampleBlock(); + ast->list_of_selects->children.at(query_num), context, Names(), to_stage, subquery_depth, true).getSampleBlock(); if (full_result_header_for_current_select.columns() != full_result_header.columns()) throw Exception("Different number of columns in UNION ALL elements:\n" @@ -87,7 +87,7 @@ InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery( = query_num == 0 ? required_result_column_names : required_result_column_names_for_other_selects[query_num]; nested_interpreters.emplace_back(std::make_unique( - ast.list_of_selects->children.at(query_num), + ast->list_of_selects->children.at(query_num), context, current_required_result_column_names, to_stage, diff --git a/dbms/src/Interpreters/InterpreterSetQuery.cpp b/dbms/src/Interpreters/InterpreterSetQuery.cpp index bd69ff2ce56..2f7c97c0ea8 100644 --- a/dbms/src/Interpreters/InterpreterSetQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSetQuery.cpp @@ -16,12 +16,12 @@ namespace ErrorCodes BlockIO InterpreterSetQuery::execute() { - const ASTSetQuery & ast = typeid_cast(*query_ptr); + const auto * ast = query_ptr->As(); - checkAccess(ast); + checkAccess(*ast); Context & target = context.getSessionContext(); - for (const auto & change : ast.changes) + for (const auto & change : ast->changes) target.setSetting(change.name, change.value); return {}; @@ -61,11 +61,11 @@ void InterpreterSetQuery::checkAccess(const ASTSetQuery & ast) void InterpreterSetQuery::executeForCurrentContext() { - const ASTSetQuery & ast = typeid_cast(*query_ptr); + const auto * ast = query_ptr->As(); - checkAccess(ast); + checkAccess(*ast); - for (const auto & change : ast.changes) + for (const auto & change : ast->changes) context.setSetting(change.name, change.value); } diff --git a/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp b/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp index ab15d1f0112..0bc734e32ee 100644 --- a/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp +++ b/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp @@ -25,16 +25,16 @@ InterpreterShowTablesQuery::InterpreterShowTablesQuery(const ASTPtr & query_ptr_ String InterpreterShowTablesQuery::getRewrittenQuery() { - const ASTShowTablesQuery & query = typeid_cast(*query_ptr); + const auto * query = query_ptr->As(); /// SHOW DATABASES - if (query.databases) + if (query->databases) return "SELECT name FROM system.databases"; - if (query.temporary && !query.from.empty()) + if (query->temporary && !query->from.empty()) throw Exception("The `FROM` and `TEMPORARY` cannot be used together in `SHOW TABLES`", ErrorCodes::SYNTAX_ERROR); - String database = query.from.empty() ? context.getCurrentDatabase() : query.from; + String database = query->from.empty() ? context.getCurrentDatabase() : query->from; /** The parameter check_database_access_rights is reset when the SHOW TABLES query is processed, * So that all clients can see a list of all databases and tables in them regardless of their access rights @@ -45,13 +45,13 @@ String InterpreterShowTablesQuery::getRewrittenQuery() std::stringstream rewritten_query; rewritten_query << "SELECT name FROM system.tables WHERE "; - if (query.temporary) + if (query->temporary) rewritten_query << "is_temporary"; else rewritten_query << "database = " << std::quoted(database, '\''); - if (!query.like.empty()) - rewritten_query << " AND name " << (query.not_like ? "NOT " : "") << "LIKE " << std::quoted(query.like, '\''); + if (!query->like.empty()) + rewritten_query << " AND name " << (query->not_like ? "NOT " : "") << "LIKE " << std::quoted(query->like, '\''); return rewritten_query.str(); } diff --git a/dbms/src/Interpreters/InterpreterUseQuery.cpp b/dbms/src/Interpreters/InterpreterUseQuery.cpp index 8dba0d55223..484e4ac8600 100644 --- a/dbms/src/Interpreters/InterpreterUseQuery.cpp +++ b/dbms/src/Interpreters/InterpreterUseQuery.cpp @@ -9,7 +9,7 @@ namespace DB BlockIO InterpreterUseQuery::execute() { - const String & new_database = typeid_cast(*query_ptr).database; + const String & new_database = query_ptr->As()->database; context.getSessionContext().setCurrentDatabase(new_database); return {}; } diff --git a/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp b/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp index 5a1f7260a4f..36ce38853f5 100644 --- a/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp +++ b/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp @@ -90,7 +90,7 @@ struct ColumnAliasesMatcher static bool needChildVisit(ASTPtr & node, const ASTPtr &) { - if (typeid_cast(node.get())) + if (node->As()) return false; return true; } @@ -196,7 +196,7 @@ bool needRewrite(ASTSelectQuery & select) if (!select.tables) return false; - auto tables = typeid_cast(select.tables.get()); + const auto * tables = select.tables->As(); if (!tables) return false; @@ -206,11 +206,11 @@ bool needRewrite(ASTSelectQuery & select) for (size_t i = 1; i < tables->children.size(); ++i) { - auto table = typeid_cast(tables->children[i].get()); + const auto * table = tables->children[i]->As(); if (!table || !table->table_join) throw Exception("Multiple JOIN expects joined tables", ErrorCodes::LOGICAL_ERROR); - auto join = typeid_cast(table->table_join.get()); + const auto * join = table->table_join->As(); if (join->kind == ASTTableJoin::Kind::Comma) throw Exception("Multiple COMMA JOIN is not supported", ErrorCodes::NOT_IMPLEMENTED); @@ -306,8 +306,8 @@ static ASTPtr makeSubqueryTemplate() ASTPtr JoinToSubqueryTransformMatcher::replaceJoin(ASTPtr ast_left, ASTPtr ast_right) { - auto left = typeid_cast(ast_left.get()); - auto right = typeid_cast(ast_right.get()); + const auto * left = ast_left->As(); + const auto * right = ast_right->As(); if (!left || !right) throw Exception("Two TablesInSelectQueryElements expected", ErrorCodes::LOGICAL_ERROR); diff --git a/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp b/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp index 612ea231bdd..85c34bc4563 100644 --- a/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp +++ b/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp @@ -239,7 +239,7 @@ void PredicateExpressionsOptimizer::setNewAliasesForInnerPredicate( if (alias == qualified_name) { String name; - if (auto * id = typeid_cast(ast.get())) + if (auto * id = ast->As()) { name = id->tryGetAlias(); if (name.empty()) diff --git a/dbms/src/Interpreters/ProcessList.cpp b/dbms/src/Interpreters/ProcessList.cpp index f1cdc946771..1443c8d9db7 100644 --- a/dbms/src/Interpreters/ProcessList.cpp +++ b/dbms/src/Interpreters/ProcessList.cpp @@ -38,7 +38,7 @@ static bool isUnlimitedQuery(const IAST * ast) return false; /// It is KILL QUERY - if (typeid_cast(ast)) + if (ast->As()) return true; /// It is SELECT FROM system.processes @@ -46,12 +46,12 @@ static bool isUnlimitedQuery(const IAST * ast) /// False negative: USE system; SELECT * FROM processes; /// False positive: SELECT * FROM system.processes CROSS JOIN (SELECT ...) - if (auto ast_selects = typeid_cast(ast)) + if (const auto * ast_selects = ast->As()) { if (!ast_selects->list_of_selects || ast_selects->list_of_selects->children.empty()) return false; - auto ast_select = typeid_cast(ast_selects->list_of_selects->children[0].get()); + const auto * ast_select = ast_selects->list_of_selects->children[0]->As(); if (!ast_select) return false; diff --git a/dbms/src/Interpreters/QueryNormalizer.cpp b/dbms/src/Interpreters/QueryNormalizer.cpp index f689eff6555..6722734d76c 100644 --- a/dbms/src/Interpreters/QueryNormalizer.cpp +++ b/dbms/src/Interpreters/QueryNormalizer.cpp @@ -149,8 +149,7 @@ void QueryNormalizer::visit(ASTTablesInSelectQueryElement & node, const ASTPtr & static bool needVisitChild(const ASTPtr & child) { - if (typeid_cast(child.get()) || - typeid_cast(child.get())) + if (child->As() || child->As()) return false; return true; } diff --git a/dbms/src/Interpreters/SyntaxAnalyzer.cpp b/dbms/src/Interpreters/SyntaxAnalyzer.cpp index 6d274e326b4..2c9496ceec4 100644 --- a/dbms/src/Interpreters/SyntaxAnalyzer.cpp +++ b/dbms/src/Interpreters/SyntaxAnalyzer.cpp @@ -112,12 +112,12 @@ void translateQualifiedNames(ASTPtr & query, const ASTSelectQuery & select_query bool hasArrayJoin(const ASTPtr & ast) { - if (const ASTFunction * function = typeid_cast(&*ast)) + if (const ASTFunction * function = ast->As()) if (function->name == "arrayJoin") return true; for (const auto & child : ast->children) - if (!typeid_cast(child.get()) && hasArrayJoin(child)) + if (!child->As() && hasArrayJoin(child)) return true; return false; @@ -213,9 +213,9 @@ void optimizeGroupBy(ASTSelectQuery * select_query, const NameSet & source_colum if (!select_query->group_expression_list) return; - const auto is_literal = [] (const ASTPtr & ast) + const auto is_literal = [] (const ASTPtr & ast) -> bool { - return typeid_cast(ast.get()); + return ast->As(); }; auto & group_exprs = select_query->group_expression_list->children; @@ -244,13 +244,9 @@ void optimizeGroupBy(ASTSelectQuery * select_query, const NameSet & source_colum continue; } - const auto & dict_name = typeid_cast(*function->arguments->children[0]) - .value.safeGet(); - + const auto & dict_name = function->arguments->children[0]->As()->value.safeGet(); const auto & dict_ptr = context.getExternalDictionaries().getDictionary(dict_name); - - const auto & attr_name = typeid_cast(*function->arguments->children[1]) - .value.safeGet(); + const auto & attr_name = function->arguments->children[1]->As()->value.safeGet(); if (!dict_ptr->isInjective(attr_name)) { @@ -328,9 +324,9 @@ void optimizeOrderBy(const ASTSelectQuery * select_query) for (const auto & elem : elems) { String name = elem->children.front()->getColumnName(); - const ASTOrderByElement & order_by_elem = typeid_cast(*elem); + const auto * order_by_elem = elem->As(); - if (elems_set.emplace(name, order_by_elem.collation ? order_by_elem.collation->getColumnName() : "").second) + if (elems_set.emplace(name, order_by_elem->collation ? order_by_elem->collation->getColumnName() : "").second) unique_elems.emplace_back(elem); } @@ -454,7 +450,7 @@ void collectJoinedColumnsFromJoinOnExpr(AnalyzedJoin & analyzed_join, const ASTT { if (IdentifierSemantic::getColumnName(ast)) { - auto * identifier = typeid_cast(ast.get()); + const auto * identifier = ast->As(); /// It's set in TranslateQualifiedNamesVisitor size_t membership = IdentifierSemantic::getMembership(*identifier); @@ -498,7 +494,7 @@ void collectJoinedColumnsFromJoinOnExpr(AnalyzedJoin & analyzed_join, const ASTT /// For equal expression find out corresponding table for each part, translate qualified names and add asts to join keys. auto add_columns_from_equals_expr = [&](const ASTPtr & expr) { - auto * func_equals = typeid_cast(expr.get()); + const auto * func_equals = expr->As(); if (!func_equals || func_equals->name != "equals") throwSyntaxException("Expected equals expression, got " + queryToString(expr) + "."); @@ -537,7 +533,7 @@ void collectJoinedColumnsFromJoinOnExpr(AnalyzedJoin & analyzed_join, const ASTT } }; - auto * func = typeid_cast(table_join.on_expression.get()); + const auto * func = table_join.on_expression->As(); if (func && func->name == "and") { for (const auto & expr : func->arguments->children) diff --git a/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp b/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp index 3d8a67ae766..40948a6840f 100644 --- a/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp +++ b/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp @@ -91,7 +91,7 @@ void TranslateQualifiedNamesMatcher::visit(ASTFunction & node, const ASTPtr &, D String func_name_lowercase = Poco::toLower(node.name); if (func_name_lowercase == "count" && func_arguments->children.size() == 1 && - typeid_cast(func_arguments->children[0].get())) + func_arguments->children[0]->As()) func_arguments->children.clear(); } @@ -173,14 +173,14 @@ void TranslateQualifiedNamesMatcher::visit(ASTExpressionList & node, const ASTPt bool has_asterisk = false; for (const auto & child : node.children) { - if (typeid_cast(child.get())) + if (child->As()) { if (tables_with_columns.empty()) throw Exception("An asterisk cannot be replaced with empty columns.", ErrorCodes::LOGICAL_ERROR); has_asterisk = true; break; } - else if (auto qa = typeid_cast(child.get())) + else if (const auto * qa = child->As()) { visit(*qa, child, data); /// check if it's OK before rewrite has_asterisk = true; @@ -197,7 +197,7 @@ void TranslateQualifiedNamesMatcher::visit(ASTExpressionList & node, const ASTPt for (const auto & child : old_children) { - if (const auto * asterisk = typeid_cast(child.get())) + if (const auto * asterisk = child->As()) { bool first_table = true; for (const auto & [table, table_columns] : tables_with_columns) @@ -214,7 +214,7 @@ void TranslateQualifiedNamesMatcher::visit(ASTExpressionList & node, const ASTPt first_table = false; } } - else if (const auto * qualified_asterisk = typeid_cast(child.get())) + else if (const auto * qualified_asterisk = child->As()) { DatabaseAndTableWithAlias ident_db_and_name(qualified_asterisk->children[0]); @@ -239,15 +239,15 @@ void TranslateQualifiedNamesMatcher::visit(ASTExpressionList & node, const ASTPt /// 'select * from a join b using id' should result one 'id' column void TranslateQualifiedNamesMatcher::extractJoinUsingColumns(const ASTPtr ast, Data & data) { - const auto & table_join = typeid_cast(*ast); + const auto * table_join = ast->As(); - if (table_join.using_expression_list) + if (table_join->using_expression_list) { - auto & keys = typeid_cast(*table_join.using_expression_list); + auto & keys = typeid_cast(*table_join->using_expression_list); for (const auto & key : keys.children) if (auto opt_column = getIdentifierName(key)) data.join_using_columns.insert(*opt_column); - else if (typeid_cast(key.get())) + else if (key->As()) data.join_using_columns.insert(key->getColumnName()); else { diff --git a/dbms/src/Interpreters/evaluateConstantExpression.cpp b/dbms/src/Interpreters/evaluateConstantExpression.cpp index ccf29968a5c..534d046fb70 100644 --- a/dbms/src/Interpreters/evaluateConstantExpression.cpp +++ b/dbms/src/Interpreters/evaluateConstantExpression.cpp @@ -60,7 +60,7 @@ std::pair> evaluateConstantExpression(co ASTPtr evaluateConstantExpressionAsLiteral(const ASTPtr & node, const Context & context) { /// Branch with string in query. - if (typeid_cast(node.get())) + if (node->As()) return node; /// Branch with TableFunction in query. @@ -73,7 +73,7 @@ ASTPtr evaluateConstantExpressionAsLiteral(const ASTPtr & node, const Context & ASTPtr evaluateConstantExpressionOrIdentifierAsLiteral(const ASTPtr & node, const Context & context) { - if (auto id = typeid_cast(node.get())) + if (const auto * id = node->As()) return std::make_shared(id->name); return evaluateConstantExpressionAsLiteral(node, context); @@ -145,10 +145,8 @@ namespace { const auto * left = fn->arguments->children.front().get(); const auto * right = fn->arguments->children.back().get(); - const auto * identifier = typeid_cast(left) ? typeid_cast(left) - : typeid_cast(right); - const auto * literal = typeid_cast(left) ? typeid_cast(left) - : typeid_cast(right); + const auto * identifier = left->As() ? left->As() : right->As(); + const auto * literal = left->As() ? left->As() : right->As(); return analyzeEquals(identifier, literal, expr); } @@ -156,15 +154,15 @@ namespace { const auto * left = fn->arguments->children.front().get(); const auto * right = fn->arguments->children.back().get(); - const auto * identifier = typeid_cast(left); - const auto * inner_fn = typeid_cast(right); + const auto * identifier = left->As(); + const auto * inner_fn = right->As(); if (!inner_fn) { return {}; } - const auto * tuple = typeid_cast(inner_fn->children.front().get()); + const auto * tuple = inner_fn->children.front()->As(); if (!tuple) { @@ -175,7 +173,7 @@ namespace for (const auto & child : tuple->children) { - const auto * literal = typeid_cast(child.get()); + const auto * literal = child->As(); const auto dnf = analyzeEquals(identifier, literal, expr); if (dnf.empty()) @@ -190,7 +188,7 @@ namespace } else if (fn->name == "or") { - const auto * args = typeid_cast(fn->children.front().get()); + const auto * args = fn->children.front()->As(); if (!args) { @@ -201,7 +199,7 @@ namespace for (const auto & arg : args->children) { - const auto dnf = analyzeFunction(typeid_cast(arg.get()), expr); + const auto dnf = analyzeFunction(arg->As(), expr); if (dnf.empty()) { @@ -215,7 +213,7 @@ namespace } else if (fn->name == "and") { - const auto * args = typeid_cast(fn->children.front().get()); + const auto * args = fn->children.front()->As(); if (!args) { @@ -226,7 +224,7 @@ namespace for (const auto & arg : args->children) { - const auto dnf = analyzeFunction(typeid_cast(arg.get()), expr); + const auto dnf = analyzeFunction(arg->As(), expr); if (dnf.empty()) { @@ -249,7 +247,7 @@ std::optional evaluateExpressionOverConstantCondition(const ASTPtr & nod // TODO: `node` may be always-false literal. - if (const auto fn = typeid_cast(node.get())) + if (const auto * fn = node->As()) { const auto dnf = analyzeFunction(fn, target_expr); diff --git a/dbms/src/Interpreters/executeQuery.cpp b/dbms/src/Interpreters/executeQuery.cpp index bba4202e7c0..95d373cb3fa 100644 --- a/dbms/src/Interpreters/executeQuery.cpp +++ b/dbms/src/Interpreters/executeQuery.cpp @@ -226,7 +226,7 @@ static std::tuple executeQueryImpl( /// Put query to process list. But don't put SHOW PROCESSLIST query itself. ProcessList::EntryPtr process_list_entry; - if (!internal && nullptr == typeid_cast(&*ast)) + if (!internal && !ast->As()) { process_list_entry = context.getProcessList().insert(query, ast.get(), context); context.setProcessListElement(&process_list_entry->get()); @@ -515,7 +515,7 @@ void executeQuery( if (!allow_into_outfile) throw Exception("INTO OUTFILE is not allowed", ErrorCodes::INTO_OUTFILE_NOT_ALLOWED); - const auto & out_file = typeid_cast(*ast_query_with_output->out_file).value.safeGet(); + const auto & out_file = ast_query_with_output->out_file->As()->value.safeGet(); out_file_buf.emplace(out_file, DBMS_DEFAULT_BUFFER_SIZE, O_WRONLY | O_EXCL | O_CREAT); out_buf = &*out_file_buf; } diff --git a/dbms/src/Interpreters/getClusterName.cpp b/dbms/src/Interpreters/getClusterName.cpp index bc32e3dbea7..b39c041218c 100644 --- a/dbms/src/Interpreters/getClusterName.cpp +++ b/dbms/src/Interpreters/getClusterName.cpp @@ -18,14 +18,14 @@ namespace ErrorCodes std::string getClusterName(const IAST & node) { - if (const ASTIdentifier * ast_id = typeid_cast(&node)) + if (const auto * ast_id = node.As()) return ast_id->name; - if (const ASTLiteral * ast_lit = typeid_cast(&node)) + if (const auto * ast_lit = node.As()) return ast_lit->value.safeGet(); /// A hack to support hyphens in cluster names. - if (const ASTFunction * ast_func = typeid_cast(&node)) + if (const auto * ast_func = node.As()) { if (ast_func->name != "minus" || !ast_func->arguments || ast_func->arguments->children.size() < 2) throw Exception("Illegal expression instead of cluster name.", ErrorCodes::BAD_ARGUMENTS); diff --git a/dbms/src/Interpreters/interpretSubquery.cpp b/dbms/src/Interpreters/interpretSubquery.cpp index a585f7edc42..76f075f2db3 100644 --- a/dbms/src/Interpreters/interpretSubquery.cpp +++ b/dbms/src/Interpreters/interpretSubquery.cpp @@ -19,9 +19,9 @@ std::shared_ptr interpretSubquery( const ASTPtr & table_expression, const Context & context, size_t subquery_depth, const Names & required_source_columns) { /// Subquery or table name. The name of the table is similar to the subquery `SELECT * FROM t`. - const ASTSubquery * subquery = typeid_cast(table_expression.get()); - const ASTFunction * function = typeid_cast(table_expression.get()); - const ASTIdentifier * table = typeid_cast(table_expression.get()); + const auto * subquery = table_expression->As(); + const auto * function = table_expression->As(); + const auto * table = table_expression->As(); if (!subquery && !table && !function) throw Exception("Table expression is undefined, Method: ExpressionAnalyzer::interpretSubquery." , ErrorCodes::LOGICAL_ERROR); diff --git a/dbms/src/Parsers/ASTFunction.cpp b/dbms/src/Parsers/ASTFunction.cpp index 2bf521571aa..5048e62c5de 100644 --- a/dbms/src/Parsers/ASTFunction.cpp +++ b/dbms/src/Parsers/ASTFunction.cpp @@ -132,7 +132,7 @@ void ASTFunction::formatImplWithoutAlias(const FormatSettings & settings, Format * Instead, add a space. * PS. You can not just ask to add parentheses - see formatImpl for ASTLiteral. */ - if (name == "negate" && typeid_cast(&*arguments->children[0])) + if (name == "negate" && arguments->children[0]->As()) settings.ostr << ' '; arguments->formatImpl(settings, state, nested_need_parens); @@ -203,7 +203,7 @@ void ASTFunction::formatImplWithoutAlias(const FormatSettings & settings, Format if (!written && 0 == strcmp(name.c_str(), "tupleElement")) { /// It can be printed in a form of 'x.1' only if right hand side is unsigned integer literal. - if (const ASTLiteral * lit = typeid_cast(arguments->children[1].get())) + if (const auto * lit = arguments->children[1]->As()) { if (lit->value.getType() == Field::Types::UInt64) { @@ -222,7 +222,7 @@ void ASTFunction::formatImplWithoutAlias(const FormatSettings & settings, Format if (frame.need_parens) settings.ostr << '('; - const ASTFunction * first_arg_func = typeid_cast(arguments->children[0].get()); + const auto * first_arg_func = arguments->children[0]->As(); if (first_arg_func && first_arg_func->name == "tuple" && first_arg_func->arguments diff --git a/dbms/src/Parsers/ASTIdentifier.cpp b/dbms/src/Parsers/ASTIdentifier.cpp index 1a9db37391a..2844963fd05 100644 --- a/dbms/src/Parsers/ASTIdentifier.cpp +++ b/dbms/src/Parsers/ASTIdentifier.cpp @@ -86,14 +86,14 @@ ASTPtr createTableIdentifier(const String & database_name, const String & table_ bool isIdentifier(const IAST * const ast) { if (ast) - return typeid_cast(ast); + return ast->As(); return false; } std::optional getIdentifierName(const IAST * const ast) { if (ast) - if (auto node = typeid_cast(ast)) + if (const auto * node = ast->As()) return node->name; return {}; } @@ -101,7 +101,7 @@ std::optional getIdentifierName(const IAST * const ast) bool getIdentifierName(const ASTPtr & ast, String & name) { if (ast) - if (auto node = typeid_cast(ast.get())) + if (const auto * node = ast->As()) { name = node->name; return true; diff --git a/dbms/src/Parsers/ASTSelectQuery.cpp b/dbms/src/Parsers/ASTSelectQuery.cpp index 3534518c1b9..f1cd92541c1 100644 --- a/dbms/src/Parsers/ASTSelectQuery.cpp +++ b/dbms/src/Parsers/ASTSelectQuery.cpp @@ -65,7 +65,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << indent_str << "WITH " << (s.hilite ? hilite_none : ""); s.one_line ? with_expression_list->formatImpl(s, state, frame) - : typeid_cast(*with_expression_list).formatImplMultiline(s, state, frame); + : with_expression_list->As()->formatImplMultiline(s, state, frame); s.ostr << s.nl_or_ws; } @@ -73,7 +73,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.one_line ? select_expression_list->formatImpl(s, state, frame) - : typeid_cast(*select_expression_list).formatImplMultiline(s, state, frame); + : select_expression_list->As()->formatImplMultiline(s, state, frame); if (tables) { @@ -98,7 +98,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << s.nl_or_ws << indent_str << "GROUP BY " << (s.hilite ? hilite_none : ""); s.one_line ? group_expression_list->formatImpl(s, state, frame) - : typeid_cast(*group_expression_list).formatImplMultiline(s, state, frame); + : group_expression_list->As()->formatImplMultiline(s, state, frame); } if (group_by_with_rollup) @@ -121,7 +121,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << s.nl_or_ws << indent_str << "ORDER BY " << (s.hilite ? hilite_none : ""); s.one_line ? order_expression_list->formatImpl(s, state, frame) - : typeid_cast(*order_expression_list).formatImplMultiline(s, state, frame); + : order_expression_list->As()->formatImplMultiline(s, state, frame); } if (limit_by_value) @@ -131,7 +131,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << " BY " << (s.hilite ? hilite_none : ""); s.one_line ? limit_by_expression_list->formatImpl(s, state, frame) - : typeid_cast(*limit_by_expression_list).formatImplMultiline(s, state, frame); + : limit_by_expression_list->As()->formatImplMultiline(s, state, frame); } if (limit_length) @@ -357,4 +357,3 @@ void ASTSelectQuery::addTableFunction(ASTPtr & table_function_ptr) } } - diff --git a/dbms/src/Parsers/ASTTablesInSelectQuery.cpp b/dbms/src/Parsers/ASTTablesInSelectQuery.cpp index 1f2adfb17cd..2f3e645a99a 100644 --- a/dbms/src/Parsers/ASTTablesInSelectQuery.cpp +++ b/dbms/src/Parsers/ASTTablesInSelectQuery.cpp @@ -208,7 +208,7 @@ void ASTArrayJoin::formatImpl(const FormatSettings & settings, FormatState & sta settings.one_line ? expression_list->formatImpl(settings, state, frame) - : typeid_cast(*expression_list).formatImplMultiline(settings, state, frame); + : expression_list->As()->formatImplMultiline(settings, state, frame); } diff --git a/dbms/src/Parsers/ExpressionElementParsers.cpp b/dbms/src/Parsers/ExpressionElementParsers.cpp index e38689467ea..786db068af7 100644 --- a/dbms/src/Parsers/ExpressionElementParsers.cpp +++ b/dbms/src/Parsers/ExpressionElementParsers.cpp @@ -1075,7 +1075,7 @@ bool ParserArrayOfLiterals::parseImpl(Pos & pos, ASTPtr & node, Expected & expec if (!literal_p.parse(pos, literal_node, expected)) return false; - arr.push_back(typeid_cast(*literal_node).value); + arr.push_back(literal_node->As()->value); } expected.add(pos, "closing square bracket"); @@ -1325,4 +1325,3 @@ bool ParserOrderByElement::parseImpl(Pos & pos, ASTPtr & node, Expected & expect } } - diff --git a/dbms/src/Parsers/IAST.h b/dbms/src/Parsers/IAST.h index 7692691073d..3d9a738a9f2 100644 --- a/dbms/src/Parsers/IAST.h +++ b/dbms/src/Parsers/IAST.h @@ -1,13 +1,14 @@ #pragma once -#include -#include -#include -#include - #include -#include +#include #include +#include +#include + +#include +#include +#include class SipHash; @@ -26,10 +27,6 @@ namespace ErrorCodes using IdentifierNameSet = std::set; -class IAST; -using ASTPtr = std::shared_ptr; -using ASTs = std::vector; - class WriteBuffer; @@ -45,6 +42,18 @@ public: IAST(const IAST &) = default; IAST & operator=(const IAST &) = default; + template + Derived * As() + { + return typeid_cast(this); + } + + template + const Derived * As() const + { + return typeid_cast(this); + } + /** Get the canonical name of the column if the element is a column */ String getColumnName() const; virtual void appendColumnName(WriteBuffer &) const diff --git a/dbms/src/Parsers/IAST_fwd.h b/dbms/src/Parsers/IAST_fwd.h new file mode 100644 index 00000000000..f5ceb8d2e41 --- /dev/null +++ b/dbms/src/Parsers/IAST_fwd.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +namespace DB { + +class IAST; +using ASTPtr = std::shared_ptr; +using ASTs = std::vector; + +} // namespace DB diff --git a/dbms/src/Parsers/ParserAlterQuery.cpp b/dbms/src/Parsers/ParserAlterQuery.cpp index 818362e9c95..1d58a49937c 100644 --- a/dbms/src/Parsers/ParserAlterQuery.cpp +++ b/dbms/src/Parsers/ParserAlterQuery.cpp @@ -202,7 +202,7 @@ bool ParserAlterCommand::parseImpl(Pos & pos, ASTPtr & node, Expected & expected if (!parser_string_literal.parse(pos, ast_from, expected)) return false; - command->from = typeid_cast(*ast_from).value.get(); + command->from = ast_from->As()->value.get(); command->type = ASTAlterCommand::FETCH_PARTITION; } else if (s_freeze.ignore(pos, expected)) @@ -229,7 +229,7 @@ bool ParserAlterCommand::parseImpl(Pos & pos, ASTPtr & node, Expected & expected if (!parser_string_literal.parse(pos, ast_with_name, expected)) return false; - command->with_name = typeid_cast(*ast_with_name).value.get(); + command->with_name = ast_with_name->As()->value.get(); } } else if (s_modify_column.ignore(pos, expected)) diff --git a/dbms/src/Parsers/ParserCreateQuery.cpp b/dbms/src/Parsers/ParserCreateQuery.cpp index fe343b31618..fb28c3bb956 100644 --- a/dbms/src/Parsers/ParserCreateQuery.cpp +++ b/dbms/src/Parsers/ParserCreateQuery.cpp @@ -126,8 +126,8 @@ bool ParserIndexDeclaration::parseImpl(Pos & pos, ASTPtr & node, Expected & expe return false; auto index = std::make_shared(); - index->name = typeid_cast(*name).name; - index->granularity = typeid_cast(*granularity).value.get(); + index->name = name->As()->name; + index->granularity = granularity->As()->value.get(); index->set(index->expr, expr); index->set(index->type, type); node = index; @@ -179,9 +179,9 @@ bool ParserColumnsOrIndicesDeclarationList::parseImpl(Pos & pos, ASTPtr & node, for (const auto & elem : list->children) { - if (typeid_cast(elem.get())) + if (elem->As()) columns->children.push_back(elem); - else if (typeid_cast(elem.get())) + else if (elem->As()) indices->children.push_back(elem); else return false; diff --git a/dbms/src/Parsers/ParserPartition.cpp b/dbms/src/Parsers/ParserPartition.cpp index 1daf4dead18..33dc47514b3 100644 --- a/dbms/src/Parsers/ParserPartition.cpp +++ b/dbms/src/Parsers/ParserPartition.cpp @@ -37,7 +37,7 @@ bool ParserPartition::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) size_t fields_count; StringRef fields_str; - const auto * tuple_ast = typeid_cast(value.get()); + const auto * tuple_ast = value->As(); if (tuple_ast && tuple_ast->name == "tuple") { const auto * arguments_ast = dynamic_cast(tuple_ast->arguments.get()); diff --git a/dbms/src/Parsers/ParserSetQuery.cpp b/dbms/src/Parsers/ParserSetQuery.cpp index 14b5b4bec5e..d925890d5e9 100644 --- a/dbms/src/Parsers/ParserSetQuery.cpp +++ b/dbms/src/Parsers/ParserSetQuery.cpp @@ -32,7 +32,7 @@ static bool parseNameValuePair(ASTSetQuery::Change & change, IParser::Pos & pos, return false; getIdentifierName(name, change.name); - change.value = typeid_cast(*value).value; + change.value = value->As()->value; return true; } diff --git a/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp b/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp index 2fa71415efb..3eefeb049d3 100644 --- a/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp +++ b/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp @@ -17,7 +17,7 @@ bool parseIdentifierOrStringLiteral(IParser::Pos & pos, Expected & expected, Str if (!ParserStringLiteral().parse(pos, res, expected)) return false; - result = typeid_cast(*res).value.safeGet(); + result = res->As()->value.safeGet(); } else result = *getIdentifierName(res); diff --git a/dbms/src/Storages/AlterCommands.cpp b/dbms/src/Storages/AlterCommands.cpp index d3790aa3a19..f432f3903dd 100644 --- a/dbms/src/Storages/AlterCommands.cpp +++ b/dbms/src/Storages/AlterCommands.cpp @@ -39,21 +39,21 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = AlterCommand::ADD_COLUMN; - const auto & ast_col_decl = typeid_cast(*command_ast->col_decl); + const auto * ast_col_decl = command_ast->col_decl->As(); - command.column_name = ast_col_decl.name; - if (ast_col_decl.type) + command.column_name = ast_col_decl->name; + if (ast_col_decl->type) { - command.data_type = data_type_factory.get(ast_col_decl.type); + command.data_type = data_type_factory.get(ast_col_decl->type); } - if (ast_col_decl.default_expression) + if (ast_col_decl->default_expression) { - command.default_kind = columnDefaultKindFromString(ast_col_decl.default_specifier); - command.default_expression = ast_col_decl.default_expression; + command.default_kind = columnDefaultKindFromString(ast_col_decl->default_specifier); + command.default_expression = ast_col_decl->default_expression; } - if (ast_col_decl.codec) - command.codec = compression_codec_factory.get(ast_col_decl.codec); + if (ast_col_decl->codec) + command.codec = compression_codec_factory.get(ast_col_decl->codec); if (command_ast->column) command.after_column = *getIdentifierName(command_ast->column); @@ -78,27 +78,27 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = AlterCommand::MODIFY_COLUMN; - const auto & ast_col_decl = typeid_cast(*command_ast->col_decl); + const auto * ast_col_decl = command_ast->col_decl->As(); - command.column_name = ast_col_decl.name; - if (ast_col_decl.type) + command.column_name = ast_col_decl->name; + if (ast_col_decl->type) { - command.data_type = data_type_factory.get(ast_col_decl.type); + command.data_type = data_type_factory.get(ast_col_decl->type); } - if (ast_col_decl.default_expression) + if (ast_col_decl->default_expression) { - command.default_kind = columnDefaultKindFromString(ast_col_decl.default_specifier); - command.default_expression = ast_col_decl.default_expression; + command.default_kind = columnDefaultKindFromString(ast_col_decl->default_specifier); + command.default_expression = ast_col_decl->default_expression; } - if (ast_col_decl.codec) - command.codec = compression_codec_factory.get(ast_col_decl.codec); + if (ast_col_decl->codec) + command.codec = compression_codec_factory.get(ast_col_decl->codec); - if (ast_col_decl.comment) + if (ast_col_decl->comment) { - const auto & ast_comment = typeid_cast(*ast_col_decl.comment); - command.comment = ast_comment.value.get(); + const auto * ast_comment = ast_col_decl->comment->As(); + command.comment = ast_comment->value.get(); } command.if_exists = command_ast->if_exists; @@ -127,12 +127,12 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.index_decl = command_ast->index_decl; command.type = AlterCommand::ADD_INDEX; - const auto & ast_index_decl = typeid_cast(*command_ast->index_decl); + const auto * ast_index_decl = command_ast->index_decl->As(); - command.index_name = ast_index_decl.name; + command.index_name = ast_index_decl->name; if (command_ast->index) - command.after_index_name = typeid_cast(*command_ast->index).name; + command.after_index_name = command_ast->index->As()->name; command.if_not_exists = command_ast->if_not_exists; @@ -145,7 +145,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = AlterCommand::DROP_INDEX; - command.index_name = typeid_cast(*(command_ast->index)).name; + command.index_name = command_ast->index->As()->name; command.if_exists = command_ast->if_exists; return command; @@ -335,7 +335,7 @@ void AlterCommand::apply(ColumnsDescription & columns_description, IndicesDescri indices_description.indices.cend(), [this](const ASTPtr & index_ast) { - return typeid_cast(*index_ast).name == index_name; + return index_ast->As()->name == index_name; })) { if (if_not_exists) @@ -354,7 +354,7 @@ void AlterCommand::apply(ColumnsDescription & columns_description, IndicesDescri indices_description.indices.end(), [this](const ASTPtr & index_ast) { - return typeid_cast(*index_ast).name == after_index_name; + return index_ast->As()->name == after_index_name; }); if (insert_it == indices_description.indices.end()) @@ -373,7 +373,7 @@ void AlterCommand::apply(ColumnsDescription & columns_description, IndicesDescri indices_description.indices.end(), [this](const ASTPtr & index_ast) { - return typeid_cast(*index_ast).name == index_name; + return index_ast->As()->name == index_name; }); if (erase_it == indices_description.indices.end()) diff --git a/dbms/src/Storages/ColumnsDescription.cpp b/dbms/src/Storages/ColumnsDescription.cpp index 92069098ebf..1d9313fe0db 100644 --- a/dbms/src/Storages/ColumnsDescription.cpp +++ b/dbms/src/Storages/ColumnsDescription.cpp @@ -158,7 +158,7 @@ void parseColumn(ReadBufferFromString & buf, ColumnsDescription & result, const String column_line; readEscapedStringUntilEOL(column_line, buf); ASTPtr ast = parseQuery(column_parser, column_line, "column parser", 0); - if (const ASTColumnDeclaration * col_ast = typeid_cast(ast.get())) + if (const auto * col_ast = ast->As()) { String column_name = col_ast->name; auto type = data_type_factory.get(col_ast->type); diff --git a/dbms/src/Storages/Kafka/StorageKafka.cpp b/dbms/src/Storages/Kafka/StorageKafka.cpp index e1c6c19d418..6b3f06e2c0c 100644 --- a/dbms/src/Storages/Kafka/StorageKafka.cpp +++ b/dbms/src/Storages/Kafka/StorageKafka.cpp @@ -409,7 +409,7 @@ void registerStorageKafka(StorageFactory & factory) String brokers; if (args_count >= 1) { - auto ast = typeid_cast(engine_args[0].get()); + const auto * ast = engine_args[0]->As(); if (ast && ast->value.getType() == Field::Types::String) { brokers = safeGet(ast->value); @@ -460,7 +460,7 @@ void registerStorageKafka(StorageFactory & factory) { engine_args[3] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[3], args.local_context); - auto ast = typeid_cast(engine_args[3].get()); + const auto * ast = engine_args[3]->As(); if (ast && ast->value.getType() == Field::Types::String) { format = safeGet(ast->value); @@ -481,7 +481,7 @@ void registerStorageKafka(StorageFactory & factory) { engine_args[4] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[4], args.local_context); - auto ast = typeid_cast(engine_args[4].get()); + const auto * ast = engine_args[4]->As(); String arg; if (ast && ast->value.getType() == Field::Types::String) { @@ -515,7 +515,7 @@ void registerStorageKafka(StorageFactory & factory) { engine_args[5] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[5], args.local_context); - auto ast = typeid_cast(engine_args[5].get()); + const auto * ast = engine_args[5]->As(); if (ast && ast->value.getType() == Field::Types::String) { schema = safeGet(ast->value); @@ -534,7 +534,7 @@ void registerStorageKafka(StorageFactory & factory) UInt64 num_consumers = 1; if (args_count >= 7) { - auto ast = typeid_cast(engine_args[6].get()); + const auto * ast = engine_args[6]->As(); if (ast && ast->value.getType() == Field::Types::UInt64) { num_consumers = safeGet(ast->value); @@ -553,7 +553,7 @@ void registerStorageKafka(StorageFactory & factory) UInt64 max_block_size = 0; if (args_count >= 8) { - auto ast = typeid_cast(engine_args[7].get()); + const auto * ast = engine_args[7]->As(); if (ast && ast->value.getType() == Field::Types::UInt64) { max_block_size = static_cast(safeGet(ast->value)); @@ -572,7 +572,7 @@ void registerStorageKafka(StorageFactory & factory) size_t skip_broken = 0; if (args_count >= 9) { - auto ast = typeid_cast(engine_args[8].get()); + const auto * ast = engine_args[8]->As(); if (ast && ast->value.getType() == Field::Types::UInt64) { skip_broken = static_cast(safeGet(ast->value)); diff --git a/dbms/src/Storages/MergeTree/KeyCondition.cpp b/dbms/src/Storages/MergeTree/KeyCondition.cpp index b64920d6233..4e631949f14 100644 --- a/dbms/src/Storages/MergeTree/KeyCondition.cpp +++ b/dbms/src/Storages/MergeTree/KeyCondition.cpp @@ -284,20 +284,20 @@ KeyCondition::KeyCondition( Block block_with_constants = getBlockWithConstants(query_info.query, query_info.syntax_analyzer_result, context); /// Trasform WHERE section to Reverse Polish notation - const ASTSelectQuery & select = typeid_cast(*query_info.query); - if (select.where_expression) + const auto * select = query_info.query->As(); + if (select->where_expression) { - traverseAST(select.where_expression, context, block_with_constants); + traverseAST(select->where_expression, context, block_with_constants); - if (select.prewhere_expression) + if (select->prewhere_expression) { - traverseAST(select.prewhere_expression, context, block_with_constants); + traverseAST(select->prewhere_expression, context, block_with_constants); rpn.emplace_back(RPNElement::FUNCTION_AND); } } - else if (select.prewhere_expression) + else if (select->prewhere_expression) { - traverseAST(select.prewhere_expression, context, block_with_constants); + traverseAST(select->prewhere_expression, context, block_with_constants); } else { @@ -321,7 +321,7 @@ static bool getConstant(const ASTPtr & expr, Block & block_with_constants, Field { String column_name = expr->getColumnName(); - if (const ASTLiteral * lit = typeid_cast(expr.get())) + if (const auto * lit = expr->As()) { /// By default block_with_constants has only one column named "_dummy". /// If block contains only constants it's may not be preprocessed by @@ -486,7 +486,7 @@ bool KeyCondition::tryPrepareSetIndex( } }; - const ASTFunction * left_arg_tuple = typeid_cast(left_arg.get()); + const auto * left_arg_tuple = left_arg->As(); if (left_arg_tuple && left_arg_tuple->name == "tuple") { const auto & tuple_elements = left_arg_tuple->arguments->children; @@ -502,7 +502,7 @@ bool KeyCondition::tryPrepareSetIndex( const ASTPtr & right_arg = args[1]; PreparedSetKey set_key; - if (typeid_cast(right_arg.get()) || typeid_cast(right_arg.get())) + if (right_arg->As() || right_arg->As()) set_key = PreparedSetKey::forSubquery(*right_arg); else set_key = PreparedSetKey::forLiteral(*right_arg, data_types); @@ -574,7 +574,7 @@ bool KeyCondition::isKeyPossiblyWrappedByMonotonicFunctionsImpl( return true; } - if (const ASTFunction * func = typeid_cast(node.get())) + if (const auto * func = node->As()) { const auto & args = func->arguments->children; if (args.size() != 1) @@ -620,9 +620,9 @@ bool KeyCondition::atomFromAST(const ASTPtr & node, const Context & context, Blo */ Field const_value; DataTypePtr const_type; - if (const ASTFunction * func = typeid_cast(node.get())) + if (const auto * func = node->As()) { - const ASTs & args = typeid_cast(*func->arguments).children; + const ASTs & args = func->arguments->As()->children; if (args.size() != 2) return false; @@ -737,7 +737,7 @@ bool KeyCondition::operatorFromAST(const ASTFunction * func, RPNElement & out) /** Also a special function `indexHint` - works as if instead of calling a function there are just parentheses * (or, the same thing - calling the function `and` from one argument). */ - const ASTs & args = typeid_cast(*func->arguments).children; + const ASTs & args = func->arguments->children; if (func->name == "not") { diff --git a/dbms/src/Storages/MergeTree/MergeTreeData.cpp b/dbms/src/Storages/MergeTree/MergeTreeData.cpp index fe0a73705b0..2bfbf03f3de 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeData.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeData.cpp @@ -405,7 +405,7 @@ ASTPtr MergeTreeData::extractKeyExpressionList(const ASTPtr & node) if (!node) return std::make_shared(); - const ASTFunction * expr_func = typeid_cast(node.get()); + const auto * expr_func = node->As(); if (expr_func && expr_func->name == "tuple") { @@ -2276,15 +2276,15 @@ size_t MergeTreeData::getPartitionSize(const std::string & partition_id) const String MergeTreeData::getPartitionIDFromQuery(const ASTPtr & ast, const Context & context) { - const auto & partition_ast = typeid_cast(*ast); + const auto * partition_ast = ast->As(); - if (!partition_ast.value) - return partition_ast.id; + if (!partition_ast->value) + return partition_ast->id; if (format_version < MERGE_TREE_DATA_MIN_FORMAT_VERSION_WITH_CUSTOM_PARTITIONING) { /// Month-partitioning specific - partition ID can be passed in the partition value. - const auto * partition_lit = typeid_cast(partition_ast.value.get()); + const auto * partition_lit = partition_ast->value->As(); if (partition_lit && partition_lit->value.getType() == Field::Types::String) { String partition_id = partition_lit->value.get(); @@ -2299,9 +2299,9 @@ String MergeTreeData::getPartitionIDFromQuery(const ASTPtr & ast, const Context /// Re-parse partition key fields using the information about expected field types. size_t fields_count = partition_key_sample.columns(); - if (partition_ast.fields_count != fields_count) + if (partition_ast->fields_count != fields_count) throw Exception( - "Wrong number of fields in the partition expression: " + toString(partition_ast.fields_count) + + "Wrong number of fields in the partition expression: " + toString(partition_ast->fields_count) + ", must be: " + toString(fields_count), ErrorCodes::INVALID_PARTITION_VALUE); @@ -2311,7 +2311,7 @@ String MergeTreeData::getPartitionIDFromQuery(const ASTPtr & ast, const Context if (fields_count) { ReadBufferFromMemory left_paren_buf("(", 1); - ReadBufferFromMemory fields_buf(partition_ast.fields_str.data, partition_ast.fields_str.size); + ReadBufferFromMemory fields_buf(partition_ast->fields_str.data, partition_ast->fields_str.size); ReadBufferFromMemory right_paren_buf(")", 1); ConcatReadBuffer buf({&left_paren_buf, &fields_buf, &right_paren_buf}); @@ -2321,7 +2321,7 @@ String MergeTreeData::getPartitionIDFromQuery(const ASTPtr & ast, const Context RowReadExtension unused; if (!input_stream.read(columns, unused)) throw Exception( - "Could not parse partition value: `" + partition_ast.fields_str.toString() + "`", + "Could not parse partition value: `" + partition_ast->fields_str.toString() + "`", ErrorCodes::INVALID_PARTITION_VALUE); for (size_t i = 0; i < fields_count; ++i) @@ -2502,7 +2502,7 @@ bool MergeTreeData::isPrimaryOrMinMaxKeyColumnPossiblyWrappedInFunctions(const A if (column_name == name) return true; - if (const ASTFunction * func = typeid_cast(node.get())) + if (const auto * func = node->As()) if (func->arguments->children.size() == 1) return isPrimaryOrMinMaxKeyColumnPossiblyWrappedInFunctions(func->arguments->children.front()); @@ -2514,7 +2514,7 @@ bool MergeTreeData::mayBenefitFromIndexForIn(const ASTPtr & left_in_operand) con /// Make sure that the left side of the IN operator contain part of the key. /// If there is a tuple on the left side of the IN operator, at least one item of the tuple /// must be part of the key (probably wrapped by a chain of some acceptable functions). - const ASTFunction * left_in_operand_tuple = typeid_cast(left_in_operand.get()); + const auto * left_in_operand_tuple = left_in_operand->As(); if (left_in_operand_tuple && left_in_operand_tuple->name == "tuple") { for (const auto & item : left_in_operand_tuple->arguments->children) diff --git a/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp b/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp index 8886b0d157b..facce694ac6 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp @@ -129,9 +129,9 @@ static RelativeSize convertAbsoluteSampleSizeToRelative(const ASTPtr & node, siz if (approx_total_rows == 0) return 1; - const ASTSampleRatio & node_sample = typeid_cast(*node); + const auto * node_sample = node->As(); - auto absolute_sample_size = node_sample.ratio.numerator / node_sample.ratio.denominator; + auto absolute_sample_size = node_sample->ratio.numerator / node_sample->ratio.denominator; return std::min(RelativeSize(1), RelativeSize(absolute_sample_size) / RelativeSize(approx_total_rows)); } @@ -295,8 +295,8 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( if (select_sample_size) { relative_sample_size.assign( - typeid_cast(*select_sample_size).ratio.numerator, - typeid_cast(*select_sample_size).ratio.denominator); + select_sample_size->As()->ratio.numerator, + select_sample_size->As()->ratio.denominator); if (relative_sample_size < 0) throw Exception("Negative sample size", ErrorCodes::ARGUMENT_OUT_OF_BOUND); @@ -304,8 +304,8 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( relative_sample_offset = 0; if (select_sample_offset) relative_sample_offset.assign( - typeid_cast(*select_sample_offset).ratio.numerator, - typeid_cast(*select_sample_offset).ratio.denominator); + select_sample_offset->As()->ratio.numerator, + select_sample_offset->As()->ratio.denominator); if (relative_sample_offset < 0) throw Exception("Negative sample offset", ErrorCodes::ARGUMENT_OUT_OF_BOUND); diff --git a/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp b/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp index 227c6bfd7f7..01ef675ecac 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp @@ -150,19 +150,19 @@ SetIndexCondition::SetIndexCondition( key_columns.insert(name); } - const ASTSelectQuery & select = typeid_cast(*query.query); + const auto * select = query.query->As(); /// Replace logical functions with bit functions. /// Working with UInt8: last bit = can be true, previous = can be false. - if (select.where_expression && select.prewhere_expression) + if (select->where_expression && select->prewhere_expression) expression_ast = makeASTFunction( "and", - select.where_expression->clone(), - select.prewhere_expression->clone()); - else if (select.where_expression) - expression_ast = select.where_expression->clone(); - else if (select.prewhere_expression) - expression_ast = select.prewhere_expression->clone(); + select->where_expression->clone(), + select->prewhere_expression->clone()); + else if (select->where_expression) + expression_ast = select->where_expression->clone(); + else if (select->prewhere_expression) + expression_ast = select->prewhere_expression->clone(); else expression_ast = std::make_shared(UNKNOWN_FIELD); @@ -239,10 +239,10 @@ bool SetIndexCondition::atomFromAST(ASTPtr & node) const { /// Function, literal or column - if (typeid_cast(node.get())) + if (node->As()) return true; - if (const auto * identifier = typeid_cast(node.get())) + if (const auto * identifier = node->As()) return key_columns.count(identifier->getColumnName()) != 0; if (auto * func = typeid_cast(node.get())) @@ -344,12 +344,12 @@ static bool checkAtomName(const String & name) bool SetIndexCondition::checkASTUseless(const ASTPtr &node, bool atomic) const { - if (const auto * func = typeid_cast(node.get())) + if (const auto * func = node->As()) { if (key_columns.count(func->getColumnName())) return false; - const ASTs & args = typeid_cast(*func->arguments).children; + const ASTs & args = func->arguments->children; if (func->name == "and" || func->name == "indexHint") return checkASTUseless(args[0], atomic) && checkASTUseless(args[1], atomic); @@ -363,9 +363,9 @@ bool SetIndexCondition::checkASTUseless(const ASTPtr &node, bool atomic) const return std::any_of(args.begin(), args.end(), [this, &atomic](const auto & arg) { return checkASTUseless(arg, atomic); }); } - else if (const auto * literal = typeid_cast(node.get())) + else if (const auto * literal = node->As()) return !atomic && literal->value.get(); - else if (const auto * identifier = typeid_cast(node.get())) + else if (const auto * identifier = node->As()) return key_columns.find(identifier->getColumnName()) == key_columns.end(); else return true; @@ -396,8 +396,7 @@ std::unique_ptr setIndexCreator( if (!node->type->arguments || node->type->arguments->children.size() != 1) throw Exception("Set index must have exactly one argument.", ErrorCodes::INCORRECT_QUERY); else if (node->type->arguments->children.size() == 1) - max_rows = typeid_cast( - *node->type->arguments->children[0]).value.get(); + max_rows = node->type->arguments->children[0]->As()->value.get(); ASTPtr expr_list = MergeTreeData::extractKeyExpressionList(node->expr->clone()); diff --git a/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp b/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp index 89a499b710a..64fc200d3b5 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp @@ -66,7 +66,7 @@ static void collectIdentifiersNoSubqueries(const ASTPtr & ast, NameSet & set) if (auto opt_name = getIdentifierName(ast)) return (void)set.insert(*opt_name); - if (typeid_cast(ast.get())) + if (ast->As()) return; for (const auto & child : ast->children) @@ -219,7 +219,7 @@ UInt64 MergeTreeWhereOptimizer::getIdentifiersColumnSize(const NameSet & identif bool MergeTreeWhereOptimizer::isConditionGood(const ASTPtr & condition) const { - const auto function = typeid_cast(condition.get()); + const auto * function = condition->As(); if (!function) return false; @@ -238,7 +238,7 @@ bool MergeTreeWhereOptimizer::isConditionGood(const ASTPtr & condition) const if (isIdentifier(left_arg)) { /// condition may be "good" if only right_arg is a constant and its value is outside the threshold - if (const auto literal = typeid_cast(right_arg)) + if (const auto * literal = right_arg->As()) { const auto & field = literal->value; const auto type = field.getType(); @@ -268,7 +268,7 @@ bool MergeTreeWhereOptimizer::isConditionGood(const ASTPtr & condition) const bool MergeTreeWhereOptimizer::hasPrimaryKeyAtoms(const ASTPtr & ast) const { - if (const auto func = typeid_cast(ast.get())) + if (const auto * func = ast->As()) { const auto & args = func->arguments->children; @@ -288,7 +288,7 @@ bool MergeTreeWhereOptimizer::hasPrimaryKeyAtoms(const ASTPtr & ast) const bool MergeTreeWhereOptimizer::isPrimaryKeyAtom(const ASTPtr & ast) const { - if (const auto func = typeid_cast(ast.get())) + if (const auto * func = ast->As()) { if (!KeyCondition::atom_map.count(func->name)) return false; @@ -314,7 +314,7 @@ bool MergeTreeWhereOptimizer::isConstant(const ASTPtr & expr) const { const auto column_name = expr->getColumnName(); - if (typeid_cast(expr.get()) + if (expr->As() || (block_with_constants.has(column_name) && block_with_constants.getByName(column_name).column->isColumnConst())) return true; @@ -334,7 +334,7 @@ bool MergeTreeWhereOptimizer::isSubsetOfTableColumns(const NameSet & identifiers bool MergeTreeWhereOptimizer::cannotBeMoved(const ASTPtr & ptr) const { - if (const auto function_ptr = typeid_cast(ptr.get())) + if (const auto * function_ptr = ptr->As()) { /// disallow arrayJoin expressions to be moved to PREWHERE for now if ("arrayJoin" == function_ptr->name) diff --git a/dbms/src/Storages/MergeTree/registerStorageMergeTree.cpp b/dbms/src/Storages/MergeTree/registerStorageMergeTree.cpp index 103be508564..e3d9ea176d6 100644 --- a/dbms/src/Storages/MergeTree/registerStorageMergeTree.cpp +++ b/dbms/src/Storages/MergeTree/registerStorageMergeTree.cpp @@ -37,7 +37,7 @@ namespace ErrorCodes */ static Names extractColumnNames(const ASTPtr & node) { - const ASTFunction * expr_func = typeid_cast(&*node); + const auto * expr_func = node->As(); if (expr_func && expr_func->name == "tuple") { @@ -474,7 +474,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) if (replicated) { - auto ast = typeid_cast(engine_args[0].get()); + const auto * ast = engine_args[0]->As(); if (ast && ast->value.getType() == Field::Types::String) zookeeper_path = safeGet(ast->value); else @@ -482,7 +482,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) "Path in ZooKeeper must be a string literal" + getMergeTreeVerboseHelp(is_extended_storage_def), ErrorCodes::BAD_ARGUMENTS); - ast = typeid_cast(engine_args[1].get()); + ast = engine_args[1]->As(); if (ast && ast->value.getType() == Field::Types::String) replica_name = safeGet(ast->value); else @@ -510,7 +510,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) else if (merging_params.mode == MergeTreeData::MergingParams::Replacing) { /// If the last element is not index_granularity or replica_name (a literal), then this is the name of the version column. - if (!engine_args.empty() && !typeid_cast(engine_args.back().get())) + if (!engine_args.empty() && !engine_args.back()->As()) { if (!getIdentifierName(engine_args.back(), merging_params.version_column)) throw Exception( @@ -523,7 +523,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) else if (merging_params.mode == MergeTreeData::MergingParams::Summing) { /// If the last element is not index_granularity or replica_name (a literal), then this is a list of summable columns. - if (!engine_args.empty() && !typeid_cast(engine_args.back().get())) + if (!engine_args.empty() && !engine_args.back()->As()) { merging_params.columns_to_sum = extractColumnNames(engine_args.back()); engine_args.pop_back(); @@ -535,7 +535,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) String error_msg = "Last parameter of GraphiteMergeTree must be name (in single quotes) of element in configuration file with Graphite options"; error_msg += getMergeTreeVerboseHelp(is_extended_storage_def); - if (auto ast = typeid_cast(engine_args.back().get())) + if (const auto * ast = engine_args.back()->As()) { if (ast->value.getType() != Field::Types::String) throw Exception(error_msg, ErrorCodes::BAD_ARGUMENTS); @@ -616,7 +616,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) order_by_ast = engine_args[1]; - auto ast = typeid_cast(engine_args.back().get()); + const auto * ast = engine_args.back()->As(); if (ast && ast->value.getType() == Field::Types::UInt64) storage_settings.index_granularity = safeGet(ast->value); else diff --git a/dbms/src/Storages/MutationCommands.cpp b/dbms/src/Storages/MutationCommands.cpp index 6ba9c23a257..f66f492c978 100644 --- a/dbms/src/Storages/MutationCommands.cpp +++ b/dbms/src/Storages/MutationCommands.cpp @@ -35,10 +35,10 @@ std::optional MutationCommand::parse(ASTAlterCommand * command) res.predicate = command->predicate; for (const ASTPtr & assignment_ast : command->update_assignments->children) { - const auto & assignment = typeid_cast(*assignment_ast); - auto insertion = res.column_to_update_expression.emplace(assignment.column_name, assignment.expression); + const auto * assignment = assignment_ast->As(); + auto insertion = res.column_to_update_expression.emplace(assignment->column_name, assignment->expression); if (!insertion.second) - throw Exception("Multiple assignments in the single statement to column `" + assignment.column_name + "`", + throw Exception("Multiple assignments in the single statement to column `" + assignment->column_name + "`", ErrorCodes::MULTIPLE_ASSIGNMENTS_TO_COLUMN); } return res; @@ -71,7 +71,7 @@ void MutationCommands::readText(ReadBuffer & in) ParserAlterCommandList p_alter_commands; auto commands_ast = parseQuery( p_alter_commands, commands_str.data(), commands_str.data() + commands_str.length(), "mutation commands list", 0); - for (ASTAlterCommand * command_ast : typeid_cast(*commands_ast).commands) + for (ASTAlterCommand * command_ast : commands_ast->As()->commands) { auto command = MutationCommand::parse(command_ast); if (!command) diff --git a/dbms/src/Storages/StorageDictionary.cpp b/dbms/src/Storages/StorageDictionary.cpp index 5aa2ea6b329..644d1cb1378 100644 --- a/dbms/src/Storages/StorageDictionary.cpp +++ b/dbms/src/Storages/StorageDictionary.cpp @@ -101,7 +101,7 @@ void registerStorageDictionary(StorageFactory & factory) ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); args.engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(args.engine_args[0], args.local_context); - String dictionary_name = typeid_cast(*args.engine_args[0]).value.safeGet(); + String dictionary_name = args.engine_args[0]->As()->value.safeGet(); return StorageDictionary::create( args.table_name, args.columns, args.context, args.attach, dictionary_name); diff --git a/dbms/src/Storages/StorageFile.cpp b/dbms/src/Storages/StorageFile.cpp index 0c221cf3393..563419dad30 100644 --- a/dbms/src/Storages/StorageFile.cpp +++ b/dbms/src/Storages/StorageFile.cpp @@ -311,7 +311,7 @@ void registerStorageFile(StorageFactory & factory) throw Exception("Unknown identifier '" + *opt_name + "' in second arg of File storage constructor", ErrorCodes::UNKNOWN_IDENTIFIER); } - else if (const ASTLiteral * literal = typeid_cast(engine_args[1].get())) + else if (const auto * literal = engine_args[1]->As()) { auto type = literal->value.getType(); if (type == Field::Types::Int64) diff --git a/dbms/src/Storages/StorageMaterializedView.cpp b/dbms/src/Storages/StorageMaterializedView.cpp index 93663badf56..d27991114e7 100644 --- a/dbms/src/Storages/StorageMaterializedView.cpp +++ b/dbms/src/Storages/StorageMaterializedView.cpp @@ -73,14 +73,14 @@ static void checkAllowedQueries(const ASTSelectQuery & query) if (!subquery) return; - if (auto ast_select = typeid_cast(subquery.get())) + if (const auto * ast_select = subquery->As()) { if (ast_select->list_of_selects->children.size() != 1) throw Exception("UNION is not supported for MATERIALIZED VIEW", ErrorCodes::QUERY_IS_NOT_SUPPORTED_IN_MATERIALIZED_VIEW); const auto & inner_query = ast_select->list_of_selects->children.at(0); - checkAllowedQueries(typeid_cast(*inner_query)); + checkAllowedQueries(*inner_query->As()); } } diff --git a/dbms/src/Storages/StorageMergeTree.cpp b/dbms/src/Storages/StorageMergeTree.cpp index ba3fe04dd89..6f5fa7ef5ee 100644 --- a/dbms/src/Storages/StorageMergeTree.cpp +++ b/dbms/src/Storages/StorageMergeTree.cpp @@ -940,7 +940,7 @@ void StorageMergeTree::attachPartition(const ASTPtr & partition, bool attach_par String partition_id; if (attach_part) - partition_id = typeid_cast(*partition).value.safeGet(); + partition_id = partition->As()->value.safeGet(); else partition_id = data.getPartitionIDFromQuery(partition, context); diff --git a/dbms/src/Storages/StorageReplicatedMergeTree.cpp b/dbms/src/Storages/StorageReplicatedMergeTree.cpp index b9bbf762c66..7c7a2d53c4d 100644 --- a/dbms/src/Storages/StorageReplicatedMergeTree.cpp +++ b/dbms/src/Storages/StorageReplicatedMergeTree.cpp @@ -3555,7 +3555,7 @@ void StorageReplicatedMergeTree::attachPartition(const ASTPtr & partition, bool String partition_id; if (attach_part) - partition_id = typeid_cast(*partition).value.safeGet(); + partition_id = partition->As()->value.safeGet(); else partition_id = data.getPartitionIDFromQuery(partition, query_context); diff --git a/dbms/src/Storages/System/StorageSystemTables.cpp b/dbms/src/Storages/System/StorageSystemTables.cpp index 498035ea7c0..0499b376d0a 100644 --- a/dbms/src/Storages/System/StorageSystemTables.cpp +++ b/dbms/src/Storages/System/StorageSystemTables.cpp @@ -240,10 +240,10 @@ protected: if (ast) { - const ASTCreateQuery & ast_create = typeid_cast(*ast); - if (ast_create.storage) + const auto * ast_create = ast->As(); + if (ast_create->storage) { - engine_full = queryToString(*ast_create.storage); + engine_full = queryToString(*ast_create->storage); static const char * const extra_head = " ENGINE = "; if (startsWith(engine_full, extra_head)) diff --git a/dbms/src/Storages/System/StorageSystemZooKeeper.cpp b/dbms/src/Storages/System/StorageSystemZooKeeper.cpp index dd7eb033514..5892967ce39 100644 --- a/dbms/src/Storages/System/StorageSystemZooKeeper.cpp +++ b/dbms/src/Storages/System/StorageSystemZooKeeper.cpp @@ -44,7 +44,7 @@ NamesAndTypesList StorageSystemZooKeeper::getNamesAndTypes() static bool extractPathImpl(const IAST & elem, String & res) { - const ASTFunction * function = typeid_cast(&elem); + const auto * function = elem.As(); if (!function) return false; @@ -59,24 +59,24 @@ static bool extractPathImpl(const IAST & elem, String & res) if (function->name == "equals") { - const ASTExpressionList & args = typeid_cast(*function->arguments); + const auto * args = function->arguments->As(); const IAST * value; - if (args.children.size() != 2) + if (args->children.size() != 2) return false; const ASTIdentifier * ident; - if ((ident = typeid_cast(&*args.children.at(0)))) - value = &*args.children.at(1); - else if ((ident = typeid_cast(&*args.children.at(1)))) - value = &*args.children.at(0); + 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 != "path") return false; - const ASTLiteral * literal = typeid_cast(value); + const auto * literal = value->As(); if (!literal) return false; @@ -95,12 +95,12 @@ static bool extractPathImpl(const IAST & elem, String & res) */ static String extractPath(const ASTPtr & query) { - const ASTSelectQuery & select = typeid_cast(*query); - if (!select.where_expression) + const auto * select = query->As(); + if (!select->where_expression) return ""; String res; - return extractPathImpl(*select.where_expression, res) ? res : ""; + return extractPathImpl(*select->where_expression, res) ? res : ""; } diff --git a/dbms/src/Storages/VirtualColumnUtils.cpp b/dbms/src/Storages/VirtualColumnUtils.cpp index b7ea5e66c37..4f3fad45d7f 100644 --- a/dbms/src/Storages/VirtualColumnUtils.cpp +++ b/dbms/src/Storages/VirtualColumnUtils.cpp @@ -106,7 +106,7 @@ static bool isValidFunction(const ASTPtr & expression, const NameSet & columns) /// Extract all subfunctions of the main conjunction, but depending only on the specified columns static void extractFunctions(const ASTPtr & expression, const NameSet & columns, std::vector & result) { - const ASTFunction * function = typeid_cast(expression.get()); + const auto * function = expression->As(); if (function && function->name == "and") { for (size_t i = 0; i < function->arguments->children.size(); ++i) @@ -136,8 +136,8 @@ static ASTPtr buildWhereExpression(const ASTs & functions) void filterBlockWithQuery(const ASTPtr & query, Block & block, const Context & context) { - const ASTSelectQuery & select = typeid_cast(*query); - if (!select.where_expression && !select.prewhere_expression) + const auto * select = query->As(); + if (!select->where_expression && !select->prewhere_expression) return; NameSet columns; @@ -146,10 +146,10 @@ void filterBlockWithQuery(const ASTPtr & query, Block & block, const Context & c /// We will create an expression that evaluates the expressions in WHERE and PREWHERE, depending only on the existing columns. std::vector functions; - if (select.where_expression) - extractFunctions(select.where_expression, columns, functions); - if (select.prewhere_expression) - extractFunctions(select.prewhere_expression, columns, functions); + if (select->where_expression) + extractFunctions(select->where_expression, columns, functions); + if (select->prewhere_expression) + extractFunctions(select->prewhere_expression, columns, functions); ASTPtr expression_ast = buildWhereExpression(functions); if (!expression_ast) diff --git a/dbms/src/Storages/transformQueryForExternalDatabase.cpp b/dbms/src/Storages/transformQueryForExternalDatabase.cpp index aea176def3b..69da7143e87 100644 --- a/dbms/src/Storages/transformQueryForExternalDatabase.cpp +++ b/dbms/src/Storages/transformQueryForExternalDatabase.cpp @@ -42,7 +42,7 @@ static void replaceConstFunction(IAST & node, const Context & context, const Nam static bool isCompatible(const IAST & node) { - if (const ASTFunction * function = typeid_cast(&node)) + if (const auto * function = node.As()) { String name = function->name; if (!(name == "and" @@ -66,7 +66,7 @@ static bool isCompatible(const IAST & node) return true; } - if (const ASTLiteral * literal = typeid_cast(&node)) + if (const auto * literal = node.As()) { /// Foreign databases often have no support for Array and Tuple literals. if (literal->value.getType() == Field::Types::Array @@ -120,7 +120,7 @@ String transformQueryForExternalDatabase( { select->where_expression = original_where; } - else if (const ASTFunction * function = typeid_cast(original_where.get())) + else if (const auto * function = original_where->As()) { if (function->name == "and") { diff --git a/dbms/src/TableFunctions/ITableFunctionXDBC.cpp b/dbms/src/TableFunctions/ITableFunctionXDBC.cpp index 455512310db..14f03493846 100644 --- a/dbms/src/TableFunctions/ITableFunctionXDBC.cpp +++ b/dbms/src/TableFunctions/ITableFunctionXDBC.cpp @@ -29,12 +29,12 @@ namespace ErrorCodes StoragePtr ITableFunctionXDBC::executeImpl(const ASTPtr & ast_function, const Context & context) const { - const ASTFunction & args_func = typeid_cast(*ast_function); + const auto * args_func = ast_function->As(); - if (!args_func.arguments) + if (!args_func->arguments) throw Exception("Table function '" + getName() + "' must have arguments.", ErrorCodes::LOGICAL_ERROR); - ASTs & args = typeid_cast(*args_func.arguments).children; + ASTs & args = typeid_cast(*args_func->arguments).children; if (args.size() != 2 && args.size() != 3) throw Exception("Table function '" + getName() + "' requires 2 or 3 arguments: " + getName() + "('DSN', table) or " + getName() + "('DSN', schema, table)", diff --git a/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp b/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp index 09ab2d3d7bb..10a3ab2b4c6 100644 --- a/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp +++ b/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp @@ -33,7 +33,7 @@ StoragePtr TableFunctionCatBoostPool::executeImpl(const ASTPtr & ast_function, c auto getStringLiteral = [](const IAST & node, const char * description) { - auto lit = typeid_cast(&node); + const auto * lit = node.As(); if (!lit) throw Exception(description + String(" must be string literal (in single quotes)."), ErrorCodes::BAD_ARGUMENTS); diff --git a/dbms/src/TableFunctions/TableFunctionMySQL.cpp b/dbms/src/TableFunctions/TableFunctionMySQL.cpp index 26dc6e200b9..6b71a1b89cb 100644 --- a/dbms/src/TableFunctions/TableFunctionMySQL.cpp +++ b/dbms/src/TableFunctions/TableFunctionMySQL.cpp @@ -87,12 +87,12 @@ DataTypePtr getDataType(const String & mysql_data_type, bool is_nullable, bool i StoragePtr TableFunctionMySQL::executeImpl(const ASTPtr & ast_function, const Context & context) const { - const ASTFunction & args_func = typeid_cast(*ast_function); + const auto * args_func = ast_function->As(); - if (!args_func.arguments) + if (!args_func->arguments) throw Exception("Table function 'mysql' must have arguments.", ErrorCodes::LOGICAL_ERROR); - ASTs & args = typeid_cast(*args_func.arguments).children; + ASTs & args = args_func->arguments->children; if (args.size() < 5 || args.size() > 7) throw Exception("Table function 'mysql' requires 5-7 parameters: MySQL('host:port', database, table, 'user', 'password'[, replace_query, 'on_duplicate_clause']).", diff --git a/dbms/src/TableFunctions/TableFunctionRemote.cpp b/dbms/src/TableFunctions/TableFunctionRemote.cpp index 716819c836d..2b4a1240bec 100644 --- a/dbms/src/TableFunctions/TableFunctionRemote.cpp +++ b/dbms/src/TableFunctions/TableFunctionRemote.cpp @@ -50,7 +50,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C auto getStringLiteral = [](const IAST & node, const char * description) { - const ASTLiteral * lit = typeid_cast(&node); + const auto * lit = node.As(); if (!lit) throw Exception(description + String(" must be string literal (in single quotes)."), ErrorCodes::BAD_ARGUMENTS); @@ -74,7 +74,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C args[arg_num] = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context); - const auto function = typeid_cast(args[arg_num].get()); + const auto * function = args[arg_num]->As(); if (function && TableFunctionFactory::instance().isTableFunctionName(function->name)) { From a7e838e328ba871de7497fe7a3a51b81d567a2ba Mon Sep 17 00:00:00 2001 From: Ivan Lezhankin Date: Mon, 11 Mar 2019 15:49:39 +0300 Subject: [PATCH 02/11] Replace all other casts to method IAST::As Also remove some redundant methods like IsIdentifier() et. al. --- dbms/programs/client/Client.cpp | 4 +- dbms/programs/copier/ClusterCopier.cpp | 14 +- .../parseAggregateFunctionParameters.cpp | 3 +- .../src/Compression/CompressionCodecDelta.cpp | 2 +- dbms/src/Compression/CompressionCodecLZ4.cpp | 3 +- dbms/src/Compression/CompressionCodecZSTD.cpp | 2 +- .../InputStreamFromASTInsertQuery.cpp | 2 +- .../DataTypes/DataTypeAggregateFunction.cpp | 2 +- dbms/src/Databases/DatabaseOrdinary.cpp | 21 ++- dbms/src/Databases/DatabasesCommon.cpp | 40 ++--- dbms/src/Interpreters/ActionsVisitor.cpp | 21 ++- dbms/src/Interpreters/AnalyzedJoin.cpp | 4 +- .../Interpreters/ArrayJoinedColumnsVisitor.h | 11 +- .../ClusterProxy/SelectStreamFactory.cpp | 2 +- .../Interpreters/CrossToInnerJoinVisitor.cpp | 14 +- dbms/src/Interpreters/DDLWorker.cpp | 8 +- .../DatabaseAndTableWithAlias.cpp | 19 +- .../ExecuteScalarSubqueriesVisitor.cpp | 16 +- dbms/src/Interpreters/ExpressionAnalyzer.cpp | 103 ++++++----- dbms/src/Interpreters/ExpressionAnalyzer.h | 1 - dbms/src/Interpreters/ExternalTablesVisitor.h | 2 +- .../Interpreters/GlobalSubqueriesVisitor.h | 13 +- dbms/src/Interpreters/IdentifierSemantic.cpp | 2 +- .../InJoinSubqueriesPreprocessor.cpp | 30 ++-- .../Interpreters/InterpreterAlterQuery.cpp | 14 +- .../Interpreters/InterpreterCheckQuery.cpp | 6 +- .../Interpreters/InterpreterCreateQuery.cpp | 46 ++--- .../src/Interpreters/InterpreterDropQuery.cpp | 16 +- dbms/src/Interpreters/InterpreterFactory.cpp | 40 ++--- .../Interpreters/InterpreterInsertQuery.cpp | 20 +-- .../InterpreterKillQueryQuery.cpp | 14 +- .../Interpreters/InterpreterRenameQuery.cpp | 10 +- .../Interpreters/InterpreterSelectQuery.cpp | 169 ++++++++++-------- .../src/Interpreters/InterpreterSelectQuery.h | 1 - .../InterpreterShowCreateQuery.cpp | 18 +- .../Interpreters/InterpreterSystemQuery.cpp | 44 ++--- .../JoinToSubqueryTransformVisitor.cpp | 15 +- .../LogicalExpressionsOptimizer.cpp | 39 ++-- .../LogicalExpressionsOptimizer.h | 9 +- ...OptimizeIfWithConstantConditionVisitor.cpp | 12 +- .../PredicateExpressionsOptimizer.cpp | 20 +-- dbms/src/Interpreters/QueryAliasesVisitor.cpp | 8 +- dbms/src/Interpreters/QueryNormalizer.cpp | 22 +-- .../RequiredSourceColumnsVisitor.cpp | 34 ++-- dbms/src/Interpreters/Set.cpp | 12 +- dbms/src/Interpreters/SyntaxAnalyzer.cpp | 48 ++--- .../TranslateQualifiedNamesVisitor.cpp | 20 +-- .../evaluateConstantExpression.cpp | 2 +- dbms/src/Interpreters/executeQuery.cpp | 4 +- dbms/src/Interpreters/interpretSubquery.cpp | 6 +- dbms/src/Interpreters/loadMetadata.cpp | 6 +- dbms/src/Parsers/ASTAlterQuery.h | 2 +- dbms/src/Parsers/ASTFunction.cpp | 2 +- dbms/src/Parsers/ASTIdentifier.cpp | 9 +- dbms/src/Parsers/ASTIdentifier.h | 3 - dbms/src/Parsers/ASTQueryWithOutput.cpp | 2 +- dbms/src/Parsers/ASTRenameQuery.h | 6 +- dbms/src/Parsers/ASTSelectQuery.cpp | 44 ++--- dbms/src/Parsers/ASTTablesInSelectQuery.cpp | 4 +- dbms/src/Parsers/ExpressionElementParsers.cpp | 16 +- dbms/src/Parsers/ExpressionListParsers.cpp | 5 +- dbms/src/Parsers/ParserDropQuery.cpp | 4 +- dbms/src/Parsers/ParserPartition.cpp | 4 +- dbms/src/Parsers/ParserQueryWithOutput.cpp | 16 +- .../Parsers/ParserSelectWithUnionQuery.cpp | 2 +- dbms/src/Parsers/ParserShowTablesQuery.cpp | 2 +- dbms/src/Parsers/ParserUnionQueryElement.cpp | 2 +- dbms/src/Parsers/parseQuery.cpp | 4 +- dbms/src/Storages/AlterCommands.cpp | 4 +- dbms/src/Storages/ColumnsDescription.cpp | 2 +- dbms/src/Storages/Kafka/StorageKafka.cpp | 4 +- dbms/src/Storages/MergeTree/KeyCondition.cpp | 4 +- dbms/src/Storages/MergeTree/MergeTreeData.cpp | 13 +- .../MergeTree/MergeTreeDataSelectExecutor.cpp | 12 +- .../MergeTree/MergeTreeSetSkippingIndex.cpp | 11 +- .../MergeTree/MergeTreeWhereOptimizer.cpp | 11 +- dbms/src/Storages/StorageBuffer.cpp | 18 +- dbms/src/Storages/StorageDistributed.cpp | 14 +- dbms/src/Storages/StorageFile.cpp | 2 +- dbms/src/Storages/StorageHDFS.cpp | 4 +- dbms/src/Storages/StorageMaterializedView.cpp | 10 +- dbms/src/Storages/StorageMerge.cpp | 10 +- dbms/src/Storages/StorageMergeTree.cpp | 6 +- dbms/src/Storages/StorageMySQL.cpp | 14 +- .../Storages/StorageReplicatedMergeTree.cpp | 14 +- dbms/src/Storages/StorageURL.cpp | 4 +- dbms/src/Storages/StorageView.cpp | 6 +- dbms/src/Storages/StorageXDBC.cpp | 6 +- dbms/src/Storages/VirtualColumnUtils.cpp | 22 +-- .../Storages/getStructureOfRemoteTable.cpp | 2 +- .../transformQueryForExternalDatabase.cpp | 8 +- .../TableFunctions/ITableFunctionFileLike.cpp | 10 +- .../src/TableFunctions/ITableFunctionXDBC.cpp | 12 +- .../TableFunctionCatBoostPool.cpp | 4 +- .../src/TableFunctions/TableFunctionMerge.cpp | 8 +- .../src/TableFunctions/TableFunctionMySQL.cpp | 14 +- .../TableFunctions/TableFunctionNumbers.cpp | 4 +- .../TableFunctions/TableFunctionRemote.cpp | 10 +- 98 files changed, 695 insertions(+), 689 deletions(-) diff --git a/dbms/programs/client/Client.cpp b/dbms/programs/client/Client.cpp index 69c9c2a5491..8c0801bf9c8 100644 --- a/dbms/programs/client/Client.cpp +++ b/dbms/programs/client/Client.cpp @@ -704,7 +704,7 @@ private: return true; } - const auto * insert = ast->As(); + auto * insert = ast->As(); if (insert && insert->data) { @@ -1228,7 +1228,7 @@ private: String current_format = format; /// The query can specify output format or output file. - if (ASTQueryWithOutput * query_with_output = dynamic_cast(&*parsed_query)) + if (const auto * query_with_output = parsed_query->As()) { if (query_with_output->out_file) { diff --git a/dbms/programs/copier/ClusterCopier.cpp b/dbms/programs/copier/ClusterCopier.cpp index 4fb037f01b4..67ddb1f13c9 100644 --- a/dbms/programs/copier/ClusterCopier.cpp +++ b/dbms/programs/copier/ClusterCopier.cpp @@ -1211,17 +1211,17 @@ protected: /// Replaces ENGINE and table name in a create query std::shared_ptr rewriteCreateQueryStorage(const ASTPtr & create_query_ast, const DatabaseAndTableName & new_table, const ASTPtr & new_storage_ast) { - ASTCreateQuery & create = typeid_cast(*create_query_ast); - auto res = std::make_shared(create); + const auto * create = create_query_ast->As(); + auto res = std::make_shared(*create); - if (create.storage == nullptr || new_storage_ast == nullptr) + if (create->storage == nullptr || new_storage_ast == nullptr) throw Exception("Storage is not specified", ErrorCodes::LOGICAL_ERROR); res->database = new_table.first; res->table = new_table.second; res->children.clear(); - res->set(res->columns_list, create.columns_list->clone()); + res->set(res->columns_list, create->columns_list->clone()); res->set(res->storage, new_storage_ast->clone()); return res; @@ -1645,7 +1645,7 @@ protected: /// Try create table (if not exists) on each shard { auto create_query_push_ast = rewriteCreateQueryStorage(task_shard.current_pull_table_create_query, task_table.table_push, task_table.engine_push_ast); - typeid_cast(*create_query_push_ast).if_not_exists = true; + create_query_push_ast->As()->if_not_exists = true; String query = queryToString(create_query_push_ast); LOG_DEBUG(log, "Create destination tables. Query: " << query); @@ -1778,8 +1778,8 @@ protected: void dropAndCreateLocalTable(const ASTPtr & create_ast) { - auto & create = typeid_cast(*create_ast); - dropLocalTableIfExists({create.database, create.table}); + const auto * create = create_ast->As(); + dropLocalTableIfExists({create->database, create->table}); InterpreterCreateQuery interpreter(create_ast, context); interpreter.execute(); diff --git a/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp b/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp index 21185f5f542..bbfe2294fde 100644 --- a/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp +++ b/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp @@ -67,8 +67,7 @@ void getAggregateFunctionNameAndParametersArray( parameters_str.data(), parameters_str.data() + parameters_str.size(), "parameters of aggregate function in " + error_context, 0); - ASTExpressionList & args_list = typeid_cast(*args_ast); - if (args_list.children.empty()) + if (args_ast->children.empty()) throw Exception("Incorrect list of parameters to aggregate function " + aggregate_function_name, ErrorCodes::BAD_ARGUMENTS); diff --git a/dbms/src/Compression/CompressionCodecDelta.cpp b/dbms/src/Compression/CompressionCodecDelta.cpp index 2c9eba1c558..986875dd95f 100644 --- a/dbms/src/Compression/CompressionCodecDelta.cpp +++ b/dbms/src/Compression/CompressionCodecDelta.cpp @@ -144,7 +144,7 @@ void registerCodecDelta(CompressionCodecFactory & factory) throw Exception("Delta codec must have 1 parameter, given " + std::to_string(arguments->children.size()), ErrorCodes::ILLEGAL_SYNTAX_FOR_CODEC_TYPE); const auto children = arguments->children; - const ASTLiteral * literal = static_cast(children[0].get()); + const auto * literal = children[0]->As(); size_t user_bytes_size = literal->value.safeGet(); if (user_bytes_size != 1 && user_bytes_size != 2 && user_bytes_size != 4 && user_bytes_size != 8) throw Exception("Delta value for delta codec can be 1, 2, 4 or 8, given " + toString(user_bytes_size), ErrorCodes::ILLEGAL_CODEC_PARAMETER); diff --git a/dbms/src/Compression/CompressionCodecLZ4.cpp b/dbms/src/Compression/CompressionCodecLZ4.cpp index c0d0fa99e1b..2340d85238f 100644 --- a/dbms/src/Compression/CompressionCodecLZ4.cpp +++ b/dbms/src/Compression/CompressionCodecLZ4.cpp @@ -86,7 +86,7 @@ void registerCodecLZ4HC(CompressionCodecFactory & factory) throw Exception("LZ4HC codec must have 1 parameter, given " + std::to_string(arguments->children.size()), ErrorCodes::ILLEGAL_SYNTAX_FOR_CODEC_TYPE); const auto children = arguments->children; - const ASTLiteral * literal = static_cast(children[0].get()); + const auto * literal = children[0]->As(); level = literal->value.safeGet(); } @@ -100,4 +100,3 @@ CompressionCodecLZ4HC::CompressionCodecLZ4HC(int level_) } } - diff --git a/dbms/src/Compression/CompressionCodecZSTD.cpp b/dbms/src/Compression/CompressionCodecZSTD.cpp index ac7e24ff9ba..1e8eb99f4be 100644 --- a/dbms/src/Compression/CompressionCodecZSTD.cpp +++ b/dbms/src/Compression/CompressionCodecZSTD.cpp @@ -73,7 +73,7 @@ void registerCodecZSTD(CompressionCodecFactory & factory) throw Exception("ZSTD codec must have 1 parameter, given " + std::to_string(arguments->children.size()), ErrorCodes::ILLEGAL_SYNTAX_FOR_CODEC_TYPE); const auto children = arguments->children; - const ASTLiteral * literal = static_cast(children[0].get()); + const auto * literal = children[0]->As(); level = literal->value.safeGet(); if (level > ZSTD_maxCLevel()) throw Exception("ZSTD codec can't have level more that " + toString(ZSTD_maxCLevel()) + ", given " + toString(level), ErrorCodes::ILLEGAL_CODEC_PARAMETER); diff --git a/dbms/src/DataStreams/InputStreamFromASTInsertQuery.cpp b/dbms/src/DataStreams/InputStreamFromASTInsertQuery.cpp index f9da736d4c4..726148e8631 100644 --- a/dbms/src/DataStreams/InputStreamFromASTInsertQuery.cpp +++ b/dbms/src/DataStreams/InputStreamFromASTInsertQuery.cpp @@ -20,7 +20,7 @@ namespace ErrorCodes InputStreamFromASTInsertQuery::InputStreamFromASTInsertQuery( const ASTPtr & ast, ReadBuffer * input_buffer_tail_part, const Block & header, Context & context) { - const ASTInsertQuery * ast_insert_query = dynamic_cast(ast.get()); + const auto * ast_insert_query = ast->As(); if (!ast_insert_query) throw Exception("Logical error: query requires data to insert, but it is not INSERT query", ErrorCodes::LOGICAL_ERROR); diff --git a/dbms/src/DataTypes/DataTypeAggregateFunction.cpp b/dbms/src/DataTypes/DataTypeAggregateFunction.cpp index 7441f3205aa..c8c1c717659 100644 --- a/dbms/src/DataTypes/DataTypeAggregateFunction.cpp +++ b/dbms/src/DataTypes/DataTypeAggregateFunction.cpp @@ -363,7 +363,7 @@ static DataTypePtr create(const ASTPtr & arguments) { function_name = *opt_name; } - else if (typeid_cast(arguments->children[0].get())) + else if (arguments->children[0]->As()) { throw Exception("Aggregate function name for data type AggregateFunction must be passed as identifier (without quotes) or function", ErrorCodes::BAD_ARGUMENTS); diff --git a/dbms/src/Databases/DatabaseOrdinary.cpp b/dbms/src/Databases/DatabaseOrdinary.cpp index 78926146169..1bed40e8e56 100644 --- a/dbms/src/Databases/DatabaseOrdinary.cpp +++ b/dbms/src/Databases/DatabaseOrdinary.cpp @@ -370,9 +370,9 @@ static ASTPtr getCreateQueryFromMetadata(const String & metadata_path, const Str if (ast) { - ASTCreateQuery & ast_create_query = typeid_cast(*ast); - ast_create_query.attach = false; - ast_create_query.database = database; + auto * ast_create_query = ast->As(); + ast_create_query->attach = false; + ast_create_query->database = database; } return ast; @@ -415,8 +415,7 @@ void DatabaseOrdinary::renameTable( ASTPtr ast = getQueryFromMetadata(detail::getTableMetadataPath(metadata_path, table_name)); if (!ast) throw Exception("There is no metadata file for table " + table_name, ErrorCodes::FILE_DOESNT_EXIST); - ASTCreateQuery & ast_create_query = typeid_cast(*ast); - ast_create_query.table = to_table_name; + ast->As()->table = to_table_name; /// NOTE Non-atomic. to_database_concrete->createTable(context, to_table_name, table, ast); @@ -534,20 +533,20 @@ void DatabaseOrdinary::alterTable( ParserCreateQuery parser; ASTPtr ast = parseQuery(parser, statement.data(), statement.data() + statement.size(), "in file " + table_metadata_path, 0); - ASTCreateQuery & ast_create_query = typeid_cast(*ast); + const auto * ast_create_query = ast->As(); ASTPtr new_columns = InterpreterCreateQuery::formatColumns(columns); ASTPtr new_indices = InterpreterCreateQuery::formatIndices(indices); - ast_create_query.columns_list->replace(ast_create_query.columns_list->columns, new_columns); + ast_create_query->columns_list->replace(ast_create_query->columns_list->columns, new_columns); - if (ast_create_query.columns_list->indices) - ast_create_query.columns_list->replace(ast_create_query.columns_list->indices, new_indices); + if (ast_create_query->columns_list->indices) + ast_create_query->columns_list->replace(ast_create_query->columns_list->indices, new_indices); else - ast_create_query.columns_list->set(ast_create_query.columns_list->indices, new_indices); + ast_create_query->columns_list->set(ast_create_query->columns_list->indices, new_indices); if (storage_modifier) - storage_modifier(*ast_create_query.storage); + storage_modifier(*ast_create_query->storage); statement = getTableDefinitionFromCreateQuery(ast); diff --git a/dbms/src/Databases/DatabasesCommon.cpp b/dbms/src/Databases/DatabasesCommon.cpp index 780140969ad..714a34461ad 100644 --- a/dbms/src/Databases/DatabasesCommon.cpp +++ b/dbms/src/Databases/DatabasesCommon.cpp @@ -26,25 +26,25 @@ namespace ErrorCodes String getTableDefinitionFromCreateQuery(const ASTPtr & query) { ASTPtr query_clone = query->clone(); - ASTCreateQuery & create = typeid_cast(*query_clone.get()); + auto * create = query_clone->As(); /// We remove everything that is not needed for ATTACH from the query. - create.attach = true; - create.database.clear(); - create.as_database.clear(); - create.as_table.clear(); - create.if_not_exists = false; - create.is_populate = false; + create->attach = true; + create->database.clear(); + create->as_database.clear(); + create->as_table.clear(); + create->if_not_exists = false; + create->is_populate = false; /// For views it is necessary to save the SELECT query itself, for the rest - on the contrary - if (!create.is_view && !create.is_materialized_view) - create.select = nullptr; + if (!create->is_view && !create->is_materialized_view) + create->select = nullptr; - create.format = nullptr; - create.out_file = nullptr; + create->format = nullptr; + create->out_file = nullptr; std::ostringstream statement_stream; - formatAST(create, statement_stream, false); + formatAST(*create, statement_stream, false); statement_stream << '\n'; return statement_stream.str(); } @@ -61,24 +61,24 @@ std::pair createTableFromDefinition( ParserCreateQuery parser; ASTPtr ast = parseQuery(parser, definition.data(), definition.data() + definition.size(), description_for_error_message, 0); - ASTCreateQuery & ast_create_query = typeid_cast(*ast); - ast_create_query.attach = true; - ast_create_query.database = database_name; + auto * ast_create_query = ast->As(); + ast_create_query->attach = true; + ast_create_query->database = database_name; /// We do not directly use `InterpreterCreateQuery::execute`, because /// - the database has not been created yet; /// - the code is simpler, since the query is already brought to a suitable form. - if (!ast_create_query.columns_list || !ast_create_query.columns_list->columns) + if (!ast_create_query->columns_list || !ast_create_query->columns_list->columns) throw Exception("Missing definition of columns.", ErrorCodes::EMPTY_LIST_OF_COLUMNS_PASSED); - ColumnsDescription columns = InterpreterCreateQuery::getColumnsDescription(*ast_create_query.columns_list->columns, context); + ColumnsDescription columns = InterpreterCreateQuery::getColumnsDescription(*ast_create_query->columns_list->columns, context); return { - ast_create_query.table, + ast_create_query->table, StorageFactory::instance().get( - ast_create_query, - database_data_path, ast_create_query.table, database_name, context, context.getGlobalContext(), + *ast_create_query, + database_data_path, ast_create_query->table, database_name, context, context.getGlobalContext(), columns, true, has_force_restore_data_flag) }; diff --git a/dbms/src/Interpreters/ActionsVisitor.cpp b/dbms/src/Interpreters/ActionsVisitor.cpp index a59fbc1c722..4ed853adc5d 100644 --- a/dbms/src/Interpreters/ActionsVisitor.cpp +++ b/dbms/src/Interpreters/ActionsVisitor.cpp @@ -122,7 +122,7 @@ SetPtr makeExplicitSet( /// 1 in (1, 2); (1, 2) in ((1, 2), (3, 4)); etc. else if (left_tuple_depth + 1 == right_tuple_depth) { - ASTFunction * set_func = typeid_cast(right_arg.get()); + const auto * set_func = right_arg->As(); if (!set_func || set_func->name != "tuple") throw Exception("Incorrect type of 2nd argument for function " + node->name @@ -263,11 +263,10 @@ void ActionsVisitor::visit(const ASTPtr & ast) }; /// If the result of the calculation already exists in the block. - if ((typeid_cast(ast.get()) || typeid_cast(ast.get())) - && actions_stack.getSampleBlock().has(getColumnName())) + if ((ast->As() || ast->As()) && actions_stack.getSampleBlock().has(getColumnName())) return; - if (auto * identifier = typeid_cast(ast.get())) + if (const auto * identifier = ast->As()) { if (!only_consts && !actions_stack.getSampleBlock().has(getColumnName())) { @@ -288,7 +287,7 @@ void ActionsVisitor::visit(const ASTPtr & ast) actions_stack.addAction(ExpressionAction::addAliases({{identifier->name, identifier->alias}})); } } - else if (ASTFunction * node = typeid_cast(ast.get())) + else if (const auto * node = ast->As()) { if (node->name == "lambda") throw Exception("Unexpected lambda expression", ErrorCodes::UNEXPECTED_EXPRESSION); @@ -383,14 +382,14 @@ void ActionsVisitor::visit(const ASTPtr & ast) auto & child = node->arguments->children[arg]; auto child_column_name = child->getColumnName(); - ASTFunction * lambda = typeid_cast(child.get()); + const auto * lambda = child->As(); if (lambda && lambda->name == "lambda") { /// If the argument is a lambda expression, just remember its approximate type. if (lambda->arguments->children.size() != 2) throw Exception("lambda requires two arguments", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - ASTFunction * lambda_args_tuple = typeid_cast(lambda->arguments->children.at(0).get()); + const auto * lambda_args_tuple = lambda->arguments->children.at(0)->As(); if (!lambda_args_tuple || lambda_args_tuple->name != "tuple") throw Exception("First argument of lambda must be a tuple", ErrorCodes::TYPE_MISMATCH); @@ -454,12 +453,12 @@ void ActionsVisitor::visit(const ASTPtr & ast) { ASTPtr child = node->arguments->children[i]; - ASTFunction * lambda = typeid_cast(child.get()); + const auto * lambda = child->As(); if (lambda && lambda->name == "lambda") { const DataTypeFunction * lambda_type = typeid_cast(argument_types[i].get()); - ASTFunction * lambda_args_tuple = typeid_cast(lambda->arguments->children.at(0).get()); - ASTs lambda_arg_asts = lambda_args_tuple->arguments->children; + const auto * lambda_args_tuple = lambda->arguments->children.at(0)->As(); + const ASTs & lambda_arg_asts = lambda_args_tuple->arguments->children; NamesAndTypesList lambda_arguments; for (size_t j = 0; j < lambda_arg_asts.size(); ++j) @@ -517,7 +516,7 @@ void ActionsVisitor::visit(const ASTPtr & ast) ExpressionAction::applyFunction(function_builder, argument_names, getColumnName())); } } - else if (ASTLiteral * literal = typeid_cast(ast.get())) + else if (const auto * literal = ast->As()) { DataTypePtr type = applyVisitor(FieldToDataType(), literal->value); diff --git a/dbms/src/Interpreters/AnalyzedJoin.cpp b/dbms/src/Interpreters/AnalyzedJoin.cpp index ce44430a5c3..3bcab24d6af 100644 --- a/dbms/src/Interpreters/AnalyzedJoin.cpp +++ b/dbms/src/Interpreters/AnalyzedJoin.cpp @@ -45,13 +45,13 @@ ExpressionActionsPtr AnalyzedJoin::createJoinedBlockActions( if (!join) return nullptr; - const auto & join_params = static_cast(*join->table_join); + const auto * join_params = join->table_join->As(); /// Create custom expression list with join keys from right table. auto expression_list = std::make_shared(); ASTs & children = expression_list->children; - if (join_params.on_expression) + if (join_params->on_expression) for (const auto & join_right_key : key_asts_right) children.emplace_back(join_right_key); diff --git a/dbms/src/Interpreters/ArrayJoinedColumnsVisitor.h b/dbms/src/Interpreters/ArrayJoinedColumnsVisitor.h index fc603ea3131..64737630537 100644 --- a/dbms/src/Interpreters/ArrayJoinedColumnsVisitor.h +++ b/dbms/src/Interpreters/ArrayJoinedColumnsVisitor.h @@ -40,11 +40,10 @@ public: static bool needChildVisit(ASTPtr & node, const ASTPtr & child) { - if (typeid_cast(node.get())) + if (node->As()) return false; - if (typeid_cast(child.get()) || - typeid_cast(child.get())) + if (child->As() || child->As()) return false; return true; @@ -52,9 +51,9 @@ public: static void visit(ASTPtr & ast, Data & data) { - if (auto * t = typeid_cast(ast.get())) + if (const auto * t = ast->As()) visit(*t, ast, data); - if (auto * t = typeid_cast(ast.get())) + if (const auto * t = ast->As()) visit(*t, ast, data); } @@ -73,7 +72,7 @@ private: const String nested_table_name = ast->getColumnName(); const String nested_table_alias = ast->getAliasOrColumnName(); - if (nested_table_alias == nested_table_name && !isIdentifier(ast)) + if (nested_table_alias == nested_table_name && !ast->As()) throw Exception("No alias for non-trivial value in ARRAY JOIN: " + nested_table_name, ErrorCodes::ALIAS_REQUIRED); if (data.array_join_alias_to_name.count(nested_table_alias) || data.aliases.count(nested_table_alias)) diff --git a/dbms/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp b/dbms/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp index b34b3d34633..644260b6a7d 100644 --- a/dbms/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp +++ b/dbms/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp @@ -98,7 +98,7 @@ void SelectStreamFactory::createForShard( if (table_func_ptr) { - auto table_function = static_cast(table_func_ptr.get()); + const auto * table_function = table_func_ptr->As(); main_table_storage = TableFunctionFactory::instance().get(table_function->name, context)->execute(table_func_ptr, context); } else diff --git a/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp b/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp index ad449899438..d601de3f403 100644 --- a/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp +++ b/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp @@ -183,7 +183,7 @@ static ASTPtr getCrossJoin(ASTSelectQuery & select, std::vector(ast.get())) + if (auto * t = ast->As()) visit(*t, ast, data); } @@ -205,19 +205,19 @@ void CrossToInnerJoinMatcher::visit(ASTSelectQuery & select, ASTPtr & ast, Data if (visitor_data.matchAny()) { - auto & join = typeid_cast(*ast_join); - join.kind = ASTTableJoin::Kind::Inner; - join.strictness = ASTTableJoin::Strictness::All; + auto * join = ast_join->As(); + join->kind = ASTTableJoin::Kind::Inner; + join->strictness = ASTTableJoin::Strictness::All; if (visitor_data.canReuseWhere()) - join.on_expression.swap(select.where_expression); + join->on_expression.swap(select.where_expression); else - join.on_expression = visitor_data.makeOnExpression(); + join->on_expression = visitor_data.makeOnExpression(); if (visitor_data.matchAll()) select.where_expression.reset(); - join.children.push_back(join.on_expression); + join->children.push_back(join->on_expression); ast = ast->clone(); /// rewrite AST in right manner data.done = true; diff --git a/dbms/src/Interpreters/DDLWorker.cpp b/dbms/src/Interpreters/DDLWorker.cpp index a0777422e87..b71e80c4189 100644 --- a/dbms/src/Interpreters/DDLWorker.cpp +++ b/dbms/src/Interpreters/DDLWorker.cpp @@ -449,6 +449,7 @@ void DDLWorker::parseQueryAndResolveHost(DDLTask & task) task.query = parseQuery(parser_query, begin, end, description, 0); } + // XXX: serious design flaw since `ASTQueryWithOnCluster` is not inherited from `IAST`! if (!task.query || !(task.query_on_cluster = dynamic_cast(task.query.get()))) throw Exception("Received unknown DDL query", ErrorCodes::UNKNOWN_TYPE_OF_QUERY); @@ -612,7 +613,7 @@ void DDLWorker::processTask(DDLTask & task, const ZooKeeperPtr & zookeeper) String rewritten_query = queryToString(rewritten_ast); LOG_DEBUG(log, "Executing query: " << rewritten_query); - if (auto ast_alter = dynamic_cast(rewritten_ast.get())) + if (const auto * ast_alter = rewritten_ast->As()) { processTaskAlter(task, ast_alter, rewritten_query, task.entry_path, zookeeper); } @@ -1211,7 +1212,8 @@ BlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, const Context & cont ASTPtr query_ptr = query_ptr_->clone(); ASTQueryWithOutput::resetOutputASTIfExist(*query_ptr); - auto query = dynamic_cast(query_ptr.get()); + // XXX: serious design flaw since `ASTQueryWithOnCluster` is not inherited from `IAST`! + auto * query = dynamic_cast(query_ptr.get()); if (!query) { throw Exception("Distributed execution is not supported for such DDL queries", ErrorCodes::NOT_IMPLEMENTED); @@ -1220,7 +1222,7 @@ BlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, const Context & cont if (!context.getSettingsRef().allow_distributed_ddl) throw Exception("Distributed DDL queries are prohibited for the user", ErrorCodes::QUERY_IS_PROHIBITED); - if (auto query_alter = dynamic_cast(query_ptr.get())) + if (const auto * query_alter = query_ptr->As()) { for (const auto & command : query_alter->command_list->commands) { diff --git a/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp b/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp index 8ff1d66ff4a..2d5e85cee2c 100644 --- a/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp +++ b/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp @@ -78,10 +78,10 @@ std::vector getSelectTablesExpression(const ASTSelec for (const auto & child : select_query.tables->children) { - ASTTablesInSelectQueryElement * tables_element = static_cast(child.get()); + const auto * tables_element = child->As(); if (tables_element->table_expression) - tables_expression.emplace_back(static_cast(tables_element->table_expression.get())); + tables_expression.emplace_back(tables_element->table_expression->As()); } return tables_expression; @@ -92,17 +92,16 @@ static const ASTTableExpression * getTableExpression(const ASTSelectQuery & sele if (!select.tables) return {}; - ASTTablesInSelectQuery & tables_in_select_query = static_cast(*select.tables); - if (tables_in_select_query.children.size() <= table_number) + const auto * tables_in_select_query = select.tables->As(); + if (tables_in_select_query->children.size() <= table_number) return {}; - ASTTablesInSelectQueryElement & tables_element = - static_cast(*tables_in_select_query.children[table_number]); + const auto * tables_element = tables_in_select_query->children[table_number]->As(); - if (!tables_element.table_expression) + if (!tables_element->table_expression) return {}; - return static_cast(tables_element.table_expression.get()); + return tables_element->table_expression->As(); } std::vector getDatabaseAndTables(const ASTSelectQuery & select_query, const String & current_database) @@ -125,7 +124,7 @@ std::optional getDatabaseAndTable(const ASTSelectQuer return {}; ASTPtr database_and_table_name = table_expression->database_and_table_name; - if (!database_and_table_name || !isIdentifier(database_and_table_name)) + if (!database_and_table_name || !database_and_table_name->As()) return {}; return DatabaseAndTableWithAlias(database_and_table_name); @@ -142,7 +141,7 @@ ASTPtr extractTableExpression(const ASTSelectQuery & select, size_t table_number return table_expression->table_function; if (table_expression->subquery) - return static_cast(table_expression->subquery.get())->children[0]; + return table_expression->subquery->children[0]; } return nullptr; diff --git a/dbms/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp b/dbms/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp index b6cbaaf181b..0e97595d47c 100644 --- a/dbms/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp +++ b/dbms/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp @@ -41,19 +41,17 @@ static ASTPtr addTypeConversion(std::unique_ptr && ast, const String bool ExecuteScalarSubqueriesMatcher::needChildVisit(ASTPtr & node, const ASTPtr & child) { /// Processed - if (typeid_cast(node.get()) || - typeid_cast(node.get())) + if (node->As() || node->As()) return false; /// Don't descend into subqueries in FROM section - if (typeid_cast(node.get())) + if (node->As()) return false; - if (typeid_cast(node.get())) + if (node->As()) { /// Do not go to FROM, JOIN, UNION. - if (typeid_cast(child.get()) || - typeid_cast(child.get())) + if (child->As() || child->As()) return false; } @@ -62,9 +60,9 @@ bool ExecuteScalarSubqueriesMatcher::needChildVisit(ASTPtr & node, const ASTPtr void ExecuteScalarSubqueriesMatcher::visit(ASTPtr & ast, Data & data) { - if (auto * t = typeid_cast(ast.get())) + if (const auto * t = ast->As()) visit(*t, ast, data); - if (auto * t = typeid_cast(ast.get())) + if (const auto * t = ast->As()) visit(*t, ast, data); } @@ -147,7 +145,7 @@ void ExecuteScalarSubqueriesMatcher::visit(const ASTFunction & func, ASTPtr & as out.push_back(&child); else for (size_t i = 0, size = func.arguments->children.size(); i < size; ++i) - if (i != 1 || !typeid_cast(func.arguments->children[i].get())) + if (i != 1 || !func.arguments->children[i]->As()) out.push_back(&func.arguments->children[i]); } } diff --git a/dbms/src/Interpreters/ExpressionAnalyzer.cpp b/dbms/src/Interpreters/ExpressionAnalyzer.cpp index 6c9089eb389..68b8526a959 100644 --- a/dbms/src/Interpreters/ExpressionAnalyzer.cpp +++ b/dbms/src/Interpreters/ExpressionAnalyzer.cpp @@ -90,8 +90,6 @@ ExpressionAnalyzer::ExpressionAnalyzer( storage = syntax->storage; rewrite_subqueries = syntax->rewrite_subqueries; - select_query = typeid_cast(query.get()); - if (!additional_source_columns.empty()) { source_columns.insert(source_columns.end(), additional_source_columns.begin(), additional_source_columns.end()); @@ -130,6 +128,8 @@ void ExpressionAnalyzer::analyzeAggregation() * Everything below (compiling temporary ExpressionActions) - only for the purpose of query analysis (type output). */ + auto * select_query = query->As(); + if (select_query && (select_query->group_expression_list || select_query->having_expression)) has_aggregation = true; @@ -149,10 +149,10 @@ void ExpressionAnalyzer::analyzeAggregation() const ASTTablesInSelectQueryElement * join = select_query->join(); if (join) { - const auto table_join = static_cast(*join->table_join); - if (table_join.using_expression_list) - getRootActions(table_join.using_expression_list, true, temp_actions); - if (table_join.on_expression) + const auto * table_join = join->table_join->As(); + if (table_join->using_expression_list) + getRootActions(table_join->using_expression_list, true, temp_actions); + if (table_join->on_expression) for (const auto & key_ast : analyzedJoin().key_asts_left) getRootActions(key_ast, true, temp_actions); @@ -250,6 +250,8 @@ void ExpressionAnalyzer::initGlobalSubqueriesAndExternalTables() void ExpressionAnalyzer::makeSetsForIndex() { + const auto * select_query = query->As(); + if (storage && select_query && storage->supportsIndexForIn()) { if (select_query->where_expression) @@ -288,7 +290,7 @@ void ExpressionAnalyzer::makeSetsForIndexImpl(const ASTPtr & node) for (auto & child : node->children) { /// Don't descend into subqueries. - if (typeid_cast(child.get())) + if (child->As()) continue; /// Don't descend into lambda functions @@ -307,7 +309,7 @@ void ExpressionAnalyzer::makeSetsForIndexImpl(const ASTPtr & node) if (storage && storage->mayBenefitFromIndexForIn(args.children.at(0), context)) { const ASTPtr & arg = args.children.at(1); - if (typeid_cast(arg.get()) || isIdentifier(arg)) + if (arg->As() || arg->As()) { if (settings.use_index_for_in_with_subqueries) tryMakeSetForIndexFromSubquery(arg); @@ -365,6 +367,8 @@ void ExpressionAnalyzer::getActionsFromJoinKeys(const ASTTableJoin & table_join, void ExpressionAnalyzer::getAggregates(const ASTPtr & ast, ExpressionActionsPtr & actions) { + const auto * select_query = query->As(); + /// There can not be aggregate functions inside the WHERE and PREWHERE. if (select_query && (ast.get() == select_query->where_expression.get() || ast.get() == select_query->prewhere_expression.get())) { @@ -436,6 +440,8 @@ void ExpressionAnalyzer::assertNoAggregates(const ASTPtr & ast, const char * des void ExpressionAnalyzer::assertSelect() const { + const auto * select_query = query->As(); + if (!select_query) throw Exception("Not a select query", ErrorCodes::LOGICAL_ERROR); } @@ -473,6 +479,8 @@ void ExpressionAnalyzer::addMultipleArrayJoinAction(ExpressionActionsPtr & actio bool ExpressionAnalyzer::appendArrayJoin(ExpressionActionsChain & chain, bool only_types) { + const auto * select_query = query->As(); + assertSelect(); bool is_array_join_left; @@ -518,6 +526,8 @@ static void appendRequiredColumns(NameSet & required_columns, const Block & samp bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_types) { + const auto * select_query = query->As(); + assertSelect(); if (!select_query->join()) @@ -526,42 +536,42 @@ bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_ty initChain(chain, source_columns); ExpressionActionsChain::Step & step = chain.steps.back(); - const auto & join_element = static_cast(*select_query->join()); - auto & join_params = static_cast(*join_element.table_join); + const auto * join_element = select_query->join()->As(); + auto * join_params = join_element->table_join->As(); - if (join_params.strictness == ASTTableJoin::Strictness::Unspecified && join_params.kind != ASTTableJoin::Kind::Cross) + if (join_params->strictness == ASTTableJoin::Strictness::Unspecified && join_params->kind != ASTTableJoin::Kind::Cross) { if (settings.join_default_strictness == "ANY") - join_params.strictness = ASTTableJoin::Strictness::Any; + join_params->strictness = ASTTableJoin::Strictness::Any; else if (settings.join_default_strictness == "ALL") - join_params.strictness = ASTTableJoin::Strictness::All; + join_params->strictness = ASTTableJoin::Strictness::All; else throw Exception("Expected ANY or ALL in JOIN section, because setting (join_default_strictness) is empty", DB::ErrorCodes::EXPECTED_ALL_OR_ANY); } - const auto & table_to_join = static_cast(*join_element.table_expression); + const auto * table_to_join = join_element->table_expression->As(); - getActionsFromJoinKeys(join_params, only_types, step.actions); + getActionsFromJoinKeys(*join_params, only_types, step.actions); /// Two JOINs are not supported with the same subquery, but different USINGs. - auto join_hash = join_element.getTreeHash(); + auto join_hash = join_element->getTreeHash(); SubqueryForSet & subquery_for_set = subqueries_for_sets[toString(join_hash.first) + "_" + toString(join_hash.second)]; /// Special case - if table name is specified on the right of JOIN, then the table has the type Join (the previously prepared mapping). /// TODO This syntax does not support specifying a database name. - if (table_to_join.database_and_table_name) + if (table_to_join->database_and_table_name) { - DatabaseAndTableWithAlias database_table(table_to_join.database_and_table_name); + DatabaseAndTableWithAlias database_table(table_to_join->database_and_table_name); StoragePtr table = context.tryGetTable(database_table.database, database_table.table); if (table) { - StorageJoin * storage_join = dynamic_cast(table.get()); + auto * storage_join = dynamic_cast(table.get()); if (storage_join) { - storage_join->assertCompatible(join_params.kind, join_params.strictness); + storage_join->assertCompatible(join_params->kind, join_params->strictness); /// TODO Check the set of keys. JoinPtr & join = storage_join->getJoin(); @@ -586,12 +596,12 @@ bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_ty { ASTPtr table; - if (table_to_join.subquery) - table = table_to_join.subquery; - else if (table_to_join.table_function) - table = table_to_join.table_function; - else if (table_to_join.database_and_table_name) - table = table_to_join.database_and_table_name; + if (table_to_join->subquery) + table = table_to_join->subquery; + else if (table_to_join->table_function) + table = table_to_join->table_function; + else if (table_to_join->database_and_table_name) + table = table_to_join->database_and_table_name; Names action_columns = joined_block_actions->getRequiredColumns(); NameSet required_columns(action_columns.begin(), action_columns.end()); @@ -609,7 +619,7 @@ bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_ty /// TODO You do not need to set this up when JOIN is only needed on remote servers. subquery_for_set.join = std::make_shared(analyzedJoin().key_names_right, settings.join_use_nulls, - settings.size_limits_for_join, join_params.kind, join_params.strictness); + settings.size_limits_for_join, join_params->kind, join_params->strictness); subquery_for_set.join->setSampleBlock(sample_block); subquery_for_set.joined_block_actions = joined_block_actions; } @@ -622,6 +632,8 @@ bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_ty bool ExpressionAnalyzer::appendPrewhere( ExpressionActionsChain & chain, bool only_types, const Names & additional_required_columns) { + const auto * select_query = query->As(); + assertSelect(); if (!select_query->prewhere_expression) @@ -695,6 +707,8 @@ bool ExpressionAnalyzer::appendPrewhere( bool ExpressionAnalyzer::appendWhere(ExpressionActionsChain & chain, bool only_types) { + const auto * select_query = query->As(); + assertSelect(); if (!select_query->where_expression) @@ -713,6 +727,8 @@ bool ExpressionAnalyzer::appendWhere(ExpressionActionsChain & chain, bool only_t bool ExpressionAnalyzer::appendGroupBy(ExpressionActionsChain & chain, bool only_types) { + const auto * select_query = query->As(); + assertAggregation(); if (!select_query->group_expression_list) @@ -733,6 +749,8 @@ bool ExpressionAnalyzer::appendGroupBy(ExpressionActionsChain & chain, bool only void ExpressionAnalyzer::appendAggregateFunctionsArguments(ExpressionActionsChain & chain, bool only_types) { + const auto * select_query = query->As(); + assertAggregation(); initChain(chain, source_columns); @@ -757,6 +775,8 @@ void ExpressionAnalyzer::appendAggregateFunctionsArguments(ExpressionActionsChai bool ExpressionAnalyzer::appendHaving(ExpressionActionsChain & chain, bool only_types) { + const auto * select_query = query->As(); + assertAggregation(); if (!select_query->having_expression) @@ -773,6 +793,8 @@ bool ExpressionAnalyzer::appendHaving(ExpressionActionsChain & chain, bool only_ void ExpressionAnalyzer::appendSelect(ExpressionActionsChain & chain, bool only_types) { + const auto * select_query = query->As(); + assertSelect(); initChain(chain, aggregated_columns); @@ -786,6 +808,8 @@ void ExpressionAnalyzer::appendSelect(ExpressionActionsChain & chain, bool only_ bool ExpressionAnalyzer::appendOrderBy(ExpressionActionsChain & chain, bool only_types) { + const auto * select_query = query->As(); + assertSelect(); if (!select_query->order_expression_list) @@ -799,7 +823,7 @@ bool ExpressionAnalyzer::appendOrderBy(ExpressionActionsChain & chain, bool only ASTs asts = select_query->order_expression_list->children; for (size_t i = 0; i < asts.size(); ++i) { - ASTOrderByElement * ast = typeid_cast(asts[i].get()); + const auto * ast = asts[i]->As(); if (!ast || ast->children.size() < 1) throw Exception("Bad order expression AST", ErrorCodes::UNKNOWN_TYPE_OF_AST_NODE); ASTPtr order_expression = ast->children.at(0); @@ -811,6 +835,8 @@ bool ExpressionAnalyzer::appendOrderBy(ExpressionActionsChain & chain, bool only bool ExpressionAnalyzer::appendLimitBy(ExpressionActionsChain & chain, bool only_types) { + const auto * select_query = query->As(); + assertSelect(); if (!select_query->limit_by_expression_list) @@ -829,6 +855,8 @@ bool ExpressionAnalyzer::appendLimitBy(ExpressionActionsChain & chain, bool only void ExpressionAnalyzer::appendProjectResult(ExpressionActionsChain & chain) const { + const auto * select_query = query->As(); + assertSelect(); initChain(chain, aggregated_columns); @@ -862,7 +890,7 @@ void ExpressionAnalyzer::appendExpression(ExpressionActionsChain & chain, const void ExpressionAnalyzer::getActionsBeforeAggregation(const ASTPtr & ast, ExpressionActionsPtr & actions, bool no_subqueries) { - ASTFunction * node = typeid_cast(ast.get()); + const auto * node = ast->As(); if (node && AggregateFunctionFactory::instance().isAggregateFunctionName(node->name)) for (auto & argument : node->arguments->children) @@ -963,21 +991,6 @@ void ExpressionAnalyzer::collectUsedColumns() if (columns_context.has_table_join) { const AnalyzedJoin & analyzed_join = analyzedJoin(); -#if 0 - std::cerr << "key_names_left: "; - for (const auto & name : analyzed_join.key_names_left) - std::cerr << "'" << name << "' "; - std::cerr << "key_names_right: "; - for (const auto & name : analyzed_join.key_names_right) - std::cerr << "'" << name << "' "; - std::cerr << "columns_from_joined_table: "; - for (const auto & column : analyzed_join.columns_from_joined_table) - std::cerr << "'" << column.name_and_type.name << '/' << column.original_name << "' "; - std::cerr << "available_joined_columns: "; - for (const auto & column : analyzed_join.available_joined_columns) - std::cerr << "'" << column.name_and_type.name << '/' << column.original_name << "' "; - std::cerr << std::endl; -#endif NameSet avaliable_columns; for (const auto & name : source_columns) avaliable_columns.insert(name.name); @@ -1012,6 +1025,8 @@ void ExpressionAnalyzer::collectUsedColumns() required.insert(column_name_type.name); } + const auto * select_query = query->As(); + /// You need to read at least one column to find the number of rows. if (select_query && required.empty()) required.insert(ExpressionActions::getSmallestColumn(source_columns)); diff --git a/dbms/src/Interpreters/ExpressionAnalyzer.h b/dbms/src/Interpreters/ExpressionAnalyzer.h index 83598aba72d..c7441efe4cb 100644 --- a/dbms/src/Interpreters/ExpressionAnalyzer.h +++ b/dbms/src/Interpreters/ExpressionAnalyzer.h @@ -211,7 +211,6 @@ public: private: ASTPtr query; - ASTSelectQuery * select_query; const Context & context; const ExtractedSettings settings; StoragePtr storage; /// The main table in FROM clause, if exists. diff --git a/dbms/src/Interpreters/ExternalTablesVisitor.h b/dbms/src/Interpreters/ExternalTablesVisitor.h index c792b3a1856..2c232ee4cbd 100644 --- a/dbms/src/Interpreters/ExternalTablesVisitor.h +++ b/dbms/src/Interpreters/ExternalTablesVisitor.h @@ -22,7 +22,7 @@ public: static void visit(ASTPtr & ast, Data & data) { - if (auto * t = typeid_cast(ast.get())) + if (const auto * t = ast->As()) visit(*t, ast, data); } diff --git a/dbms/src/Interpreters/GlobalSubqueriesVisitor.h b/dbms/src/Interpreters/GlobalSubqueriesVisitor.h index a394a7cf567..07c7c6d084e 100644 --- a/dbms/src/Interpreters/GlobalSubqueriesVisitor.h +++ b/dbms/src/Interpreters/GlobalSubqueriesVisitor.h @@ -56,7 +56,7 @@ public: ASTPtr table_name; ASTPtr subquery_or_table_name; - if (isIdentifier(subquery_or_table_name_or_table_expression)) + if (subquery_or_table_name_or_table_expression->As()) { table_name = subquery_or_table_name_or_table_expression; subquery_or_table_name = table_name; @@ -115,7 +115,7 @@ public: auto database_and_table_name = createTableIdentifier("", external_table_name); - if (auto ast_table_expr = typeid_cast(subquery_or_table_name_or_table_expression.get())) + if (auto * ast_table_expr = subquery_or_table_name_or_table_expression->As()) { ast_table_expr->subquery.reset(); ast_table_expr->database_and_table_name = database_and_table_name; @@ -140,16 +140,16 @@ public: static void visit(ASTPtr & ast, Data & data) { - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) visit(*t, ast, data); - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) visit(*t, ast, data); } static bool needChildVisit(ASTPtr &, const ASTPtr & child) { /// We do not go into subqueries. - if (typeid_cast(child.get())) + if (child->As()) return false; return true; } @@ -168,8 +168,7 @@ private: /// GLOBAL JOIN static void visit(ASTTablesInSelectQueryElement & table_elem, ASTPtr &, Data & data) { - if (table_elem.table_join - && static_cast(*table_elem.table_join).locality == ASTTableJoin::Locality::Global) + if (table_elem.table_join && table_elem.table_join->As()->locality == ASTTableJoin::Locality::Global) { data.addExternalStorage(table_elem.table_expression); data.has_global_subqueries = true; diff --git a/dbms/src/Interpreters/IdentifierSemantic.cpp b/dbms/src/Interpreters/IdentifierSemantic.cpp index 35597d1b915..7ea2f8ac761 100644 --- a/dbms/src/Interpreters/IdentifierSemantic.cpp +++ b/dbms/src/Interpreters/IdentifierSemantic.cpp @@ -144,7 +144,7 @@ void IdentifierSemantic::setColumnLongName(ASTIdentifier & identifier, const Dat String IdentifierSemantic::columnNormalName(const ASTIdentifier & identifier, const DatabaseAndTableWithAlias & db_and_table) { ASTPtr copy = identifier.clone(); - setColumnNormalName(typeid_cast(*copy), db_and_table); + setColumnNormalName(*copy->As(), db_and_table); return copy->getAliasOrColumnName(); } diff --git a/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp b/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp index e0be0d068e0..ce15eaf7683 100644 --- a/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp +++ b/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp @@ -30,7 +30,7 @@ namespace template void forEachNonGlobalSubquery(IAST * node, F && f) { - if (ASTFunction * function = typeid_cast(node)) + if (auto * function = node->As()) { if (function->name == "in" || function->name == "notIn") { @@ -40,16 +40,16 @@ void forEachNonGlobalSubquery(IAST * node, F && f) /// Pass into other functions, as subquery could be in aggregate or in lambda functions. } - else if (ASTTablesInSelectQueryElement * join = typeid_cast(node)) + else if (const auto * join = node->As()) { if (join->table_join && join->table_expression) { - auto & table_join = static_cast(*join->table_join); - if (table_join.locality != ASTTableJoin::Locality::Global) + auto * table_join = join->table_join->As(); + if (table_join->locality != ASTTableJoin::Locality::Global) { - auto & subquery = static_cast(*join->table_expression).subquery; + auto & subquery = join->table_expression->As()->subquery; if (subquery) - f(subquery.get(), nullptr, &table_join); + f(subquery.get(), nullptr, table_join); } return; } @@ -59,7 +59,7 @@ void forEachNonGlobalSubquery(IAST * node, F && f) /// Descent into all children, but not into subqueries of other kind (scalar subqueries), that are irrelevant to us. for (auto & child : node->children) - if (!typeid_cast(child.get())) + if (!child->As()) forEachNonGlobalSubquery(child.get(), f); } @@ -69,7 +69,7 @@ void forEachNonGlobalSubquery(IAST * node, F && f) template void forEachTable(IAST * node, F && f) { - if (auto table_expression = typeid_cast(node)) + if (auto * table_expression = node->As()) { auto & database_and_table = table_expression->database_and_table_name; if (database_and_table) @@ -103,15 +103,15 @@ void InJoinSubqueriesPreprocessor::process(ASTSelectQuery * query) const if (!query->tables) return; - ASTTablesInSelectQuery & tables_in_select_query = static_cast(*query->tables); - if (tables_in_select_query.children.empty()) + const auto * tables_in_select_query = query->tables->As(); + if (tables_in_select_query->children.empty()) return; - ASTTablesInSelectQueryElement & tables_element = static_cast(*tables_in_select_query.children[0]); - if (!tables_element.table_expression) + const auto * tables_element = tables_in_select_query->children[0]->As(); + if (!tables_element->table_expression) return; - ASTTableExpression * table_expression = static_cast(tables_element.table_expression.get()); + const auto * table_expression = tables_element->table_expression->As(); /// If not ordinary table, skip it. if (!table_expression->database_and_table_name) @@ -143,7 +143,7 @@ void InJoinSubqueriesPreprocessor::process(ASTSelectQuery * query) const { if (function) { - ASTFunction * concrete = static_cast(function); + auto * concrete = function->As(); if (concrete->name == "in") concrete->name = "globalIn"; @@ -157,7 +157,7 @@ void InJoinSubqueriesPreprocessor::process(ASTSelectQuery * query) const throw Exception("Logical error: unexpected function name " + concrete->name, ErrorCodes::LOGICAL_ERROR); } else if (table_join) - static_cast(*table_join).locality = ASTTableJoin::Locality::Global; + table_join->As()->locality = ASTTableJoin::Locality::Global; else throw Exception("Logical error: unexpected AST node", ErrorCodes::LOGICAL_ERROR); } diff --git a/dbms/src/Interpreters/InterpreterAlterQuery.cpp b/dbms/src/Interpreters/InterpreterAlterQuery.cpp index c28c8aef32f..dd03e8682e9 100644 --- a/dbms/src/Interpreters/InterpreterAlterQuery.cpp +++ b/dbms/src/Interpreters/InterpreterAlterQuery.cpp @@ -30,25 +30,25 @@ InterpreterAlterQuery::InterpreterAlterQuery(const ASTPtr & query_ptr_, const Co BlockIO InterpreterAlterQuery::execute() { - auto & alter = typeid_cast(*query_ptr); + const auto * alter = query_ptr->As(); - if (!alter.cluster.empty()) - return executeDDLQueryOnCluster(query_ptr, context, {alter.database}); + if (!alter->cluster.empty()) + return executeDDLQueryOnCluster(query_ptr, context, {alter->database}); - const String & table_name = alter.table; - String database_name = alter.database.empty() ? context.getCurrentDatabase() : alter.database; + const String & table_name = alter->table; + String database_name = alter->database.empty() ? context.getCurrentDatabase() : alter->database; StoragePtr table = context.getTable(database_name, table_name); /// Add default database to table identifiers that we can encounter in e.g. default expressions, /// mutation expression, etc. AddDefaultDatabaseVisitor visitor(database_name); - ASTPtr command_list_ptr = alter.command_list->ptr(); + ASTPtr command_list_ptr = alter->command_list->ptr(); visitor.visit(command_list_ptr); AlterCommands alter_commands; PartitionCommands partition_commands; MutationCommands mutation_commands; - for (ASTAlterCommand * command_ast : alter.command_list->commands) + for (ASTAlterCommand * command_ast : alter->command_list->commands) { if (auto alter_command = AlterCommand::parse(command_ast)) alter_commands.emplace_back(std::move(*alter_command)); diff --git a/dbms/src/Interpreters/InterpreterCheckQuery.cpp b/dbms/src/Interpreters/InterpreterCheckQuery.cpp index 84788fd0685..9caa33d57e9 100644 --- a/dbms/src/Interpreters/InterpreterCheckQuery.cpp +++ b/dbms/src/Interpreters/InterpreterCheckQuery.cpp @@ -19,9 +19,9 @@ InterpreterCheckQuery::InterpreterCheckQuery(const ASTPtr & query_ptr_, const Co BlockIO InterpreterCheckQuery::execute() { - ASTCheckQuery & alter = typeid_cast(*query_ptr); - String & table_name = alter.table; - String database_name = alter.database.empty() ? context.getCurrentDatabase() : alter.database; + const auto * alter = query_ptr->As(); + const String & table_name = alter->table; + String database_name = alter->database.empty() ? context.getCurrentDatabase() : alter->database; StoragePtr table = context.getTable(database_name, table_name); diff --git a/dbms/src/Interpreters/InterpreterCreateQuery.cpp b/dbms/src/Interpreters/InterpreterCreateQuery.cpp index f056d4204b5..b7cd28485d5 100644 --- a/dbms/src/Interpreters/InterpreterCreateQuery.cpp +++ b/dbms/src/Interpreters/InterpreterCreateQuery.cpp @@ -196,51 +196,51 @@ static ColumnsDeclarationAndModifiers parseColumns(const ASTExpressionList & col for (const auto & ast : column_list_ast.children) { - auto & col_decl = typeid_cast(*ast); + auto * col_decl = ast->As(); DataTypePtr column_type = nullptr; - if (col_decl.type) + if (col_decl->type) { - column_type = DataTypeFactory::instance().get(col_decl.type); - columns.emplace_back(col_decl.name, column_type); + column_type = DataTypeFactory::instance().get(col_decl->type); + columns.emplace_back(col_decl->name, column_type); } else /// we're creating dummy DataTypeUInt8 in order to prevent the NullPointerException in ExpressionActions - columns.emplace_back(col_decl.name, std::make_shared()); + columns.emplace_back(col_decl->name, std::make_shared()); /// add column to postprocessing if there is a default_expression specified - if (col_decl.default_expression) + if (col_decl->default_expression) { - defaulted_columns.emplace_back(&columns.back(), &col_decl); + defaulted_columns.emplace_back(&columns.back(), col_decl); /** for columns with explicitly-specified type create two expressions: * 1. default_expression aliased as column name with _tmp suffix * 2. conversion of expression (1) to explicitly-specified type alias as column name */ - if (col_decl.type) + if (col_decl->type) { - const auto & final_column_name = col_decl.name; + const auto & final_column_name = col_decl->name; const auto tmp_column_name = final_column_name + "_tmp"; const auto data_type_ptr = columns.back().type.get(); default_expr_list->children.emplace_back(setAlias( makeASTFunction("CAST", std::make_shared(tmp_column_name), std::make_shared(data_type_ptr->getName())), final_column_name)); - default_expr_list->children.emplace_back(setAlias(col_decl.default_expression->clone(), tmp_column_name)); + default_expr_list->children.emplace_back(setAlias(col_decl->default_expression->clone(), tmp_column_name)); } else - default_expr_list->children.emplace_back(setAlias(col_decl.default_expression->clone(), col_decl.name)); + default_expr_list->children.emplace_back(setAlias(col_decl->default_expression->clone(), col_decl->name)); } - if (col_decl.codec) + if (col_decl->codec) { - auto codec = CompressionCodecFactory::instance().get(col_decl.codec, column_type); - codecs.emplace(col_decl.name, codec); + auto codec = CompressionCodecFactory::instance().get(col_decl->codec, column_type); + codecs.emplace(col_decl->name, codec); } - if (col_decl.comment) + if (col_decl->comment) { - if (auto comment_str = typeid_cast(*col_decl.comment).value.get(); !comment_str.empty()) - comments.emplace(col_decl.name, comment_str); + if (auto comment_str = col_decl->comment->As()->value.get(); !comment_str.empty()) + comments.emplace(col_decl->name, comment_str); } } @@ -682,17 +682,17 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) BlockIO InterpreterCreateQuery::execute() { - ASTCreateQuery & create = typeid_cast(*query_ptr); - checkAccess(create); - ASTQueryWithOutput::resetOutputASTIfExist(create); + auto * create = query_ptr->As(); + checkAccess(*create); + ASTQueryWithOutput::resetOutputASTIfExist(*create); /// CREATE|ATTACH DATABASE - if (!create.database.empty() && create.table.empty()) + if (!create->database.empty() && create->table.empty()) { - return createDatabase(create); + return createDatabase(*create); } else - return createTable(create); + return createTable(*create); } diff --git a/dbms/src/Interpreters/InterpreterDropQuery.cpp b/dbms/src/Interpreters/InterpreterDropQuery.cpp index c90017721c1..568025aff8b 100644 --- a/dbms/src/Interpreters/InterpreterDropQuery.cpp +++ b/dbms/src/Interpreters/InterpreterDropQuery.cpp @@ -31,17 +31,17 @@ InterpreterDropQuery::InterpreterDropQuery(const ASTPtr & query_ptr_, Context & BlockIO InterpreterDropQuery::execute() { - ASTDropQuery & drop = typeid_cast(*query_ptr); + auto * drop = query_ptr->As(); - checkAccess(drop); + checkAccess(*drop); - if (!drop.cluster.empty()) - return executeDDLQueryOnCluster(query_ptr, context, {drop.database}); + if (!drop->cluster.empty()) + return executeDDLQueryOnCluster(query_ptr, context, {drop->database}); - if (!drop.table.empty()) - return executeToTable(drop.database, drop.table, drop.kind, drop.if_exists, drop.temporary); - else if (!drop.database.empty()) - return executeToDatabase(drop.database, drop.kind, drop.if_exists); + if (!drop->table.empty()) + return executeToTable(drop->database, drop->table, drop->kind, drop->if_exists, drop->temporary); + else if (!drop->database.empty()) + return executeToDatabase(drop->database, drop->kind, drop->if_exists); else throw Exception("Database and table names is empty.", ErrorCodes::LOGICAL_ERROR); } diff --git a/dbms/src/Interpreters/InterpreterFactory.cpp b/dbms/src/Interpreters/InterpreterFactory.cpp index 5d1b259cc0d..0a5f12d8ee8 100644 --- a/dbms/src/Interpreters/InterpreterFactory.cpp +++ b/dbms/src/Interpreters/InterpreterFactory.cpp @@ -80,95 +80,95 @@ std::unique_ptr InterpreterFactory::get(ASTPtr & query, Context & { ProfileEvents::increment(ProfileEvents::Query); - if (typeid_cast(query.get())) + if (query->As()) { /// This is internal part of ASTSelectWithUnionQuery. /// Even if there is SELECT without union, it is represented by ASTSelectWithUnionQuery with single ASTSelectQuery as a child. return std::make_unique(query, context, Names{}, stage); } - else if (typeid_cast(query.get())) + else if (query->As()) { ProfileEvents::increment(ProfileEvents::SelectQuery); return std::make_unique(query, context, Names{}, stage); } - else if (typeid_cast(query.get())) + else if (query->As()) { ProfileEvents::increment(ProfileEvents::InsertQuery); /// readonly is checked inside InterpreterInsertQuery bool allow_materialized = static_cast(context.getSettingsRef().insert_allow_materialized_columns); return std::make_unique(query, context, allow_materialized); } - else if (typeid_cast(query.get())) + else if (query->As()) { /// readonly and allow_ddl are checked inside InterpreterCreateQuery return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { /// readonly and allow_ddl are checked inside InterpreterDropQuery return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { throwIfNoAccess(context); return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { /// readonly is checked inside InterpreterSetQuery return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { throwIfNoAccess(context); return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { throwIfNoAccess(context); return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { return std::make_unique(query, context); } - else if (typeid_cast(query.get())) + else if (query->As()) { throwIfNoAccess(context); return std::make_unique(query, context); diff --git a/dbms/src/Interpreters/InterpreterInsertQuery.cpp b/dbms/src/Interpreters/InterpreterInsertQuery.cpp index 71f12212172..3e630cd9201 100644 --- a/dbms/src/Interpreters/InterpreterInsertQuery.cpp +++ b/dbms/src/Interpreters/InterpreterInsertQuery.cpp @@ -92,16 +92,16 @@ Block InterpreterInsertQuery::getSampleBlock(const ASTInsertQuery & query, const BlockIO InterpreterInsertQuery::execute() { - ASTInsertQuery & query = typeid_cast(*query_ptr); - checkAccess(query); - StoragePtr table = getTable(query); + const auto * query = query_ptr->As(); + checkAccess(*query); + StoragePtr table = getTable(*query); auto table_lock = table->lockStructure(true, context.getCurrentQueryId()); /// We create a pipeline of several streams, into which we will write data. BlockOutputStreamPtr out; - out = std::make_shared(query.database, query.table, table, context, query_ptr, query.no_destination); + out = std::make_shared(query->database, query->table, table, context, query_ptr, query->no_destination); /// Do not squash blocks if it is a sync INSERT into Distributed, since it lead to double bufferization on client and server side. /// Client-side bufferization might cause excessive timeouts (especially in case of big blocks). @@ -110,7 +110,7 @@ BlockIO InterpreterInsertQuery::execute() out = std::make_shared( out, table->getSampleBlock(), context.getSettingsRef().min_insert_block_size_rows, context.getSettingsRef().min_insert_block_size_bytes); } - auto query_sample_block = getSampleBlock(query, table); + auto query_sample_block = getSampleBlock(*query, table); /// Actually we don't know structure of input blocks from query/table, /// because some clients break insertion protocol (columns != header) @@ -125,10 +125,10 @@ BlockIO InterpreterInsertQuery::execute() res.out = std::move(out); /// What type of query: INSERT or INSERT SELECT? - if (query.select) + if (query->select) { /// Passing 1 as subquery_depth will disable limiting size of intermediate result. - InterpreterSelectWithUnionQuery interpreter_select{query.select, context, {}, QueryProcessingStage::Complete, 1}; + InterpreterSelectWithUnionQuery interpreter_select{query->select, context, {}, QueryProcessingStage::Complete, 1}; res.in = interpreter_select.execute().in; @@ -145,7 +145,7 @@ BlockIO InterpreterInsertQuery::execute() throw Exception("Cannot insert column " + name_type.name + ", because it is MATERIALIZED column.", ErrorCodes::ILLEGAL_COLUMN); } } - else if (query.data && !query.has_tail) /// can execute without additional data + else if (query->data && !query->has_tail) /// can execute without additional data { res.in = std::make_shared(query_ptr, nullptr, query_sample_block, context); res.in = std::make_shared(res.in, res.out); @@ -171,8 +171,8 @@ void InterpreterInsertQuery::checkAccess(const ASTInsertQuery & query) std::pair InterpreterInsertQuery::getDatabaseTable() const { - ASTInsertQuery & query = typeid_cast(*query_ptr); - return {query.database, query.table}; + const auto * query = query_ptr->As(); + return {query->database, query->table}; } } diff --git a/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp b/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp index 66f6248f672..f3bcbb5010f 100644 --- a/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp +++ b/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp @@ -172,13 +172,13 @@ public: BlockIO InterpreterKillQueryQuery::execute() { - ASTKillQueryQuery & query = typeid_cast(*query_ptr); + const auto * query = query_ptr->As(); - if (!query.cluster.empty()) + if (!query->cluster.empty()) return executeDDLQueryOnCluster(query_ptr, context, {"system"}); BlockIO res_io; - switch (query.type) + switch (query->type) { case ASTKillQueryQuery::Type::Query: { @@ -192,13 +192,13 @@ BlockIO InterpreterKillQueryQuery::execute() auto header = processes_block.cloneEmpty(); header.insert(0, {ColumnString::create(), std::make_shared(), "kill_status"}); - if (!query.sync || query.test) + if (!query->sync || query->test) { MutableColumns res_columns = header.cloneEmptyColumns(); for (const auto & query_desc : queries_to_stop) { - auto code = (query.test) ? CancellationCode::Unknown : process_list.sendCancelToQuery(query_desc.query_id, query_desc.user, true); + auto code = (query->test) ? CancellationCode::Unknown : process_list.sendCancelToQuery(query_desc.query_id, query_desc.user, true); insertResultRow(query_desc.source_num, code, processes_block, header, res_columns); } @@ -237,7 +237,7 @@ BlockIO InterpreterKillQueryQuery::execute() auto mutation_id = mutation_id_col.getDataAt(i).toString(); CancellationCode code = CancellationCode::Unknown; - if (!query.test) + if (!query->test) { auto storage = context.tryGetTable(database_name, table_name); if (!storage) @@ -261,7 +261,7 @@ BlockIO InterpreterKillQueryQuery::execute() Block InterpreterKillQueryQuery::getSelectResult(const String & columns, const String & table) { String select_query = "SELECT " + columns + " FROM " + table; - auto & where_expression = static_cast(*query_ptr).where_expression; + auto & where_expression = query_ptr->As()->where_expression; if (where_expression) select_query += " WHERE " + queryToString(where_expression); diff --git a/dbms/src/Interpreters/InterpreterRenameQuery.cpp b/dbms/src/Interpreters/InterpreterRenameQuery.cpp index e3fbe1f1de8..328fbed55fb 100644 --- a/dbms/src/Interpreters/InterpreterRenameQuery.cpp +++ b/dbms/src/Interpreters/InterpreterRenameQuery.cpp @@ -36,12 +36,12 @@ struct RenameDescription BlockIO InterpreterRenameQuery::execute() { - ASTRenameQuery & rename = typeid_cast(*query_ptr); + const auto * rename = query_ptr->As(); - if (!rename.cluster.empty()) + if (!rename->cluster.empty()) { NameSet databases; - for (const auto & elem : rename.elements) + for (const auto & elem : rename->elements) { databases.emplace(elem.from.database); databases.emplace(elem.to.database); @@ -58,7 +58,7 @@ BlockIO InterpreterRenameQuery::execute() */ std::vector descriptions; - descriptions.reserve(rename.elements.size()); + descriptions.reserve(rename->elements.size()); /// To avoid deadlocks, we must acquire locks for tables in same order in any different RENAMES. struct UniqueTableName @@ -80,7 +80,7 @@ BlockIO InterpreterRenameQuery::execute() /// Don't allow to drop tables (that we are renaming); don't allow to create tables in places where tables will be renamed. std::map> table_guards; - for (const auto & elem : rename.elements) + for (const auto & elem : rename->elements) { descriptions.emplace_back(elem, current_database); diff --git a/dbms/src/Interpreters/InterpreterSelectQuery.cpp b/dbms/src/Interpreters/InterpreterSelectQuery.cpp index 8fca2827fd9..f868098bd33 100644 --- a/dbms/src/Interpreters/InterpreterSelectQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSelectQuery.cpp @@ -139,7 +139,6 @@ InterpreterSelectQuery::InterpreterSelectQuery( bool modify_inplace) /// NOTE: the query almost always should be cloned because it will be modified during analysis. : query_ptr(modify_inplace ? query_ptr_ : query_ptr_->clone()) - , query(typeid_cast(*query_ptr)) , context(context_) , to_stage(to_stage_) , subquery_depth(subquery_depth_) @@ -157,7 +156,7 @@ InterpreterSelectQuery::InterpreterSelectQuery( max_streams = settings.max_threads; - ASTPtr table_expression = extractTableExpression(query, 0); + ASTPtr table_expression = extractTableExpression(*query_ptr->As(), 0); bool is_table_func = false; bool is_subquery = false; @@ -210,13 +209,15 @@ InterpreterSelectQuery::InterpreterSelectQuery( if (!only_analyze) { - if (query.sample_size() && (input || !storage || !storage->supportsSampling())) + const auto * query = query_ptr->As(); + + if (query->sample_size() && (input || !storage || !storage->supportsSampling())) throw Exception("Illegal SAMPLE: table doesn't support sampling", ErrorCodes::SAMPLING_NOT_SUPPORTED); - if (query.final() && (input || !storage || !storage->supportsFinal())) + if (query->final() && (input || !storage || !storage->supportsFinal())) throw Exception((!input && storage) ? "Storage " + storage->getName() + " doesn't support FINAL" : "Illegal FINAL", ErrorCodes::ILLEGAL_FINAL); - if (query.prewhere_expression && (input || !storage || !storage->supportsPrewhere())) + if (query->prewhere_expression && (input || !storage || !storage->supportsPrewhere())) throw Exception((!input && storage) ? "Storage " + storage->getName() + " doesn't support PREWHERE" : "Illegal PREWHERE", ErrorCodes::ILLEGAL_PREWHERE); /// Save the new temporary tables in the query context @@ -265,7 +266,7 @@ InterpreterSelectQuery::InterpreterSelectQuery( void InterpreterSelectQuery::getDatabaseAndTableNames(String & database_name, String & table_name) { - if (auto db_and_table = getDatabaseAndTable(query, 0)) + if (auto db_and_table = getDatabaseAndTable(*query_ptr->As(), 0)) { table_name = db_and_table->table; database_name = db_and_table->database; @@ -366,15 +367,16 @@ InterpreterSelectQuery::AnalysisResult InterpreterSelectQuery::analyzeExpression ExpressionActionsChain chain(context); Names additional_required_columns_after_prewhere; + const auto * query = query_ptr->As(); - if (storage && query.sample_size()) + if (storage && query->sample_size()) { Names columns_for_sampling = storage->getColumnsRequiredForSampling(); additional_required_columns_after_prewhere.insert(additional_required_columns_after_prewhere.end(), columns_for_sampling.begin(), columns_for_sampling.end()); } - if (storage && query.final()) + if (storage && query->final()) { Names columns_for_final = storage->getColumnsRequiredForFinal(); additional_required_columns_after_prewhere.insert(additional_required_columns_after_prewhere.end(), @@ -386,7 +388,7 @@ InterpreterSelectQuery::AnalysisResult InterpreterSelectQuery::analyzeExpression has_prewhere = true; res.prewhere_info = std::make_shared( - chain.steps.front().actions, query.prewhere_expression->getColumnName()); + chain.steps.front().actions, query->prewhere_expression->getColumnName()); chain.addStep(); } @@ -506,8 +508,10 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt query_info.syntax_analyzer_result = syntax_analyzer_result; query_info.sets = query_analyzer->getPreparedSets(); + const auto * query = query_ptr->As(); + /// Try transferring some condition from WHERE to PREWHERE if enabled and viable - if (settings.optimize_move_to_prewhere && query.where_expression && !query.prewhere_expression && !query.final()) + if (settings.optimize_move_to_prewhere && query->where_expression && !query->prewhere_expression && !query->final()) MergeTreeWhereOptimizer{query_info, context, merge_tree.getData(), query_analyzer->getRequiredSourceColumns(), log}; }; @@ -549,11 +553,12 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt if (to_stage > QueryProcessingStage::FetchColumns) { /// Now we will compose block streams that perform the necessary actions. + const auto * query = query_ptr->As(); /// Do I need to aggregate in a separate row rows that have not passed max_rows_to_group_by. bool aggregate_overflow_row = expressions.need_aggregate && - query.group_by_with_totals && + query->group_by_with_totals && settings.max_rows_to_group_by && settings.group_by_overflow_mode == OverflowMode::ANY && settings.totals_mode != TotalsMode::AFTER_HAVING_EXCLUSIVE; @@ -562,14 +567,14 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt bool aggregate_final = expressions.need_aggregate && to_stage > QueryProcessingStage::WithMergeableState && - !query.group_by_with_totals && !query.group_by_with_rollup && !query.group_by_with_cube; + !query->group_by_with_totals && !query->group_by_with_rollup && !query->group_by_with_cube; if (expressions.first_stage) { if (expressions.hasJoin()) { - const ASTTableJoin & join = static_cast(*query.join()->table_join); - if (join.kind == ASTTableJoin::Kind::Full || join.kind == ASTTableJoin::Kind::Right) + const auto * join = query->join()->table_join->As(); + if (join->kind == ASTTableJoin::Kind::Full || join->kind == ASTTableJoin::Kind::Right) pipeline.stream_with_non_joined_data = expressions.before_join->createStreamWithNonJoinedDataIfFullOrRightJoin( pipeline.firstStream()->getHeader(), settings.max_block_size); @@ -598,10 +603,10 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt if (expressions.has_order_by) executeOrder(pipeline); - if (expressions.has_order_by && query.limit_length) + if (expressions.has_order_by && query->limit_length) executeDistinct(pipeline, false, expressions.selected_columns); - if (query.limit_length) + if (query->limit_length) executePreLimit(pipeline); } @@ -623,20 +628,20 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt if (!aggregate_final) { - if (query.group_by_with_totals) + if (query->group_by_with_totals) { - bool final = !query.group_by_with_rollup && !query.group_by_with_cube; + bool final = !query->group_by_with_rollup && !query->group_by_with_cube; executeTotalsAndHaving(pipeline, expressions.has_having, expressions.before_having, aggregate_overflow_row, final); } - if (query.group_by_with_rollup) + if (query->group_by_with_rollup) executeRollupOrCube(pipeline, Modificator::ROLLUP); - else if (query.group_by_with_cube) + else if (query->group_by_with_cube) executeRollupOrCube(pipeline, Modificator::CUBE); - if ((query.group_by_with_rollup || query.group_by_with_cube) && expressions.has_having) + if ((query->group_by_with_rollup || query->group_by_with_cube) && expressions.has_having) { - if (query.group_by_with_totals) + if (query->group_by_with_totals) throw Exception("WITH TOTALS and WITH ROLLUP or CUBE are not supported together in presence of HAVING", ErrorCodes::NOT_IMPLEMENTED); executeHaving(pipeline, expressions.before_having); } @@ -647,28 +652,28 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt executeExpression(pipeline, expressions.before_order_and_select); executeDistinct(pipeline, true, expressions.selected_columns); - need_second_distinct_pass = query.distinct && pipeline.hasMoreThanOneStream(); + need_second_distinct_pass = query->distinct && pipeline.hasMoreThanOneStream(); } else { - need_second_distinct_pass = query.distinct && pipeline.hasMoreThanOneStream(); + need_second_distinct_pass = query->distinct && pipeline.hasMoreThanOneStream(); - if (query.group_by_with_totals && !aggregate_final) + if (query->group_by_with_totals && !aggregate_final) { - bool final = !query.group_by_with_rollup && !query.group_by_with_cube; + bool final = !query->group_by_with_rollup && !query->group_by_with_cube; executeTotalsAndHaving(pipeline, expressions.has_having, expressions.before_having, aggregate_overflow_row, final); } - if ((query.group_by_with_rollup || query.group_by_with_cube) && !aggregate_final) + if ((query->group_by_with_rollup || query->group_by_with_cube) && !aggregate_final) { - if (query.group_by_with_rollup) + if (query->group_by_with_rollup) executeRollupOrCube(pipeline, Modificator::ROLLUP); - else if (query.group_by_with_cube) + else if (query->group_by_with_cube) executeRollupOrCube(pipeline, Modificator::CUBE); if (expressions.has_having) { - if (query.group_by_with_totals) + if (query->group_by_with_totals) throw Exception("WITH TOTALS and WITH ROLLUP or CUBE are not supported together in presence of HAVING", ErrorCodes::NOT_IMPLEMENTED); executeHaving(pipeline, expressions.before_having); } @@ -681,7 +686,7 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt * but there is no aggregation, then on the remote servers ORDER BY was made * - therefore, we merge the sorted streams from remote servers. */ - if (!expressions.first_stage && !expressions.need_aggregate && !(query.group_by_with_totals && !aggregate_final)) + if (!expressions.first_stage && !expressions.need_aggregate && !(query->group_by_with_totals && !aggregate_final)) executeMergeSorted(pipeline); else /// Otherwise, just sort. executeOrder(pipeline); @@ -690,14 +695,14 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt /** Optimization - if there are several sources and there is LIMIT, then first apply the preliminary LIMIT, * limiting the number of rows in each up to `offset + limit`. */ - if (query.limit_length && pipeline.hasMoreThanOneStream() && !query.distinct && !expressions.has_limit_by && !settings.extremes) + if (query->limit_length && pipeline.hasMoreThanOneStream() && !query->distinct && !expressions.has_limit_by && !settings.extremes) { executePreLimit(pipeline); } if (need_second_distinct_pass - || query.limit_length - || query.limit_by_expression_list + || query->limit_length + || query->limit_by_expression_list || pipeline.stream_with_non_joined_data) { need_merge_streams = true; @@ -764,7 +769,7 @@ static std::pair getLimitLengthAndOffset(const ASTSelectQuery & return {length, offset}; } -static UInt64 getLimitForSorting(ASTSelectQuery & query, const Context & context) +static UInt64 getLimitForSorting(const ASTSelectQuery & query, const Context & context) { /// Partial sort can be done if there is LIMIT but no DISTINCT or LIMIT BY. if (!query.distinct && !query.limit_by_expression_list) @@ -938,21 +943,22 @@ void InterpreterSelectQuery::executeFetchColumns( } UInt64 max_block_size = settings.max_block_size; + const auto * query = query_ptr->As(); - auto [limit_length, limit_offset] = getLimitLengthAndOffset(query, context); + auto [limit_length, limit_offset] = getLimitLengthAndOffset(*query, context); /** Optimization - if not specified DISTINCT, WHERE, GROUP, HAVING, ORDER, LIMIT BY but LIMIT is specified, and limit + offset < max_block_size, * then as the block size we will use limit + offset (not to read more from the table than requested), * and also set the number of threads to 1. */ - if (!query.distinct - && !query.prewhere_expression - && !query.where_expression - && !query.group_expression_list - && !query.having_expression - && !query.order_expression_list - && !query.limit_by_expression_list - && query.limit_length + if (!query->distinct + && !query->prewhere_expression + && !query->where_expression + && !query->group_expression_list + && !query->having_expression + && !query->order_expression_list + && !query->limit_by_expression_list + && query->limit_length && !query_analyzer->hasAggregation() && limit_length + limit_offset < max_block_size) { @@ -974,7 +980,7 @@ void InterpreterSelectQuery::executeFetchColumns( /// If we need less number of columns that subquery have - update the interpreter. if (required_columns.size() < source_header.columns()) { - ASTPtr subquery = extractTableExpression(query, 0); + ASTPtr subquery = extractTableExpression(*query, 0); if (!subquery) throw Exception("Subquery expected", ErrorCodes::LOGICAL_ERROR); @@ -1072,9 +1078,9 @@ void InterpreterSelectQuery::executeFetchColumns( void InterpreterSelectQuery::executeWhere(Pipeline & pipeline, const ExpressionActionsPtr & expression, bool remove_fiter) { - pipeline.transform([&](auto & stream) - { - stream = std::make_shared(stream, expression, query.where_expression->getColumnName(), remove_fiter); + pipeline.transform([&](auto & stream) { + stream = std::make_shared( + stream, expression, query_ptr->As()->where_expression->getColumnName(), remove_fiter); }); } @@ -1200,9 +1206,9 @@ void InterpreterSelectQuery::executeMergeAggregated(Pipeline & pipeline, bool ov void InterpreterSelectQuery::executeHaving(Pipeline & pipeline, const ExpressionActionsPtr & expression) { - pipeline.transform([&](auto & stream) - { - stream = std::make_shared(stream, expression, query.having_expression->getColumnName()); + pipeline.transform([&](auto & stream) { + stream = std::make_shared( + stream, expression, query_ptr->As()->having_expression->getColumnName()); }); } @@ -1214,8 +1220,13 @@ void InterpreterSelectQuery::executeTotalsAndHaving(Pipeline & pipeline, bool ha const Settings & settings = context.getSettingsRef(); pipeline.firstStream() = std::make_shared( - pipeline.firstStream(), overflow_row, expression, - has_having ? query.having_expression->getColumnName() : "", settings.totals_mode, settings.totals_auto_threshold, final); + pipeline.firstStream(), + overflow_row, + expression, + has_having ? query_ptr->As()->having_expression->getColumnName() : "", + settings.totals_mode, + settings.totals_auto_threshold, + final); } void InterpreterSelectQuery::executeRollupOrCube(Pipeline & pipeline, Modificator modificator) @@ -1258,7 +1269,7 @@ void InterpreterSelectQuery::executeExpression(Pipeline & pipeline, const Expres } -static SortDescription getSortDescription(ASTSelectQuery & query) +static SortDescription getSortDescription(const ASTSelectQuery & query) { SortDescription order_descr; order_descr.reserve(query.order_expression_list->children.size()); @@ -1280,8 +1291,10 @@ static SortDescription getSortDescription(ASTSelectQuery & query) void InterpreterSelectQuery::executeOrder(Pipeline & pipeline) { - SortDescription order_descr = getSortDescription(query); - UInt64 limit = getLimitForSorting(query, context); + const auto * query = query_ptr->As(); + + SortDescription order_descr = getSortDescription(*query); + UInt64 limit = getLimitForSorting(*query, context); const Settings & settings = context.getSettingsRef(); @@ -1311,8 +1324,10 @@ void InterpreterSelectQuery::executeOrder(Pipeline & pipeline) void InterpreterSelectQuery::executeMergeSorted(Pipeline & pipeline) { - SortDescription order_descr = getSortDescription(query); - UInt64 limit = getLimitForSorting(query, context); + const auto * query = query_ptr->As(); + + SortDescription order_descr = getSortDescription(*query); + UInt64 limit = getLimitForSorting(*query, context); const Settings & settings = context.getSettingsRef(); @@ -1347,15 +1362,17 @@ void InterpreterSelectQuery::executeProjection(Pipeline & pipeline, const Expres void InterpreterSelectQuery::executeDistinct(Pipeline & pipeline, bool before_order, Names columns) { - if (query.distinct) + const auto * query = query_ptr->As(); + + if (query->distinct) { const Settings & settings = context.getSettingsRef(); - auto [limit_length, limit_offset] = getLimitLengthAndOffset(query, context); + auto [limit_length, limit_offset] = getLimitLengthAndOffset(*query, context); UInt64 limit_for_distinct = 0; /// If after this stage of DISTINCT ORDER BY is not executed, then you can get no more than limit_length + limit_offset of different rows. - if (!query.order_expression_list || !before_order) + if (!query->order_expression_list || !before_order) limit_for_distinct = limit_length + limit_offset; pipeline.transform([&](auto & stream) @@ -1389,10 +1406,12 @@ void InterpreterSelectQuery::executeUnion(Pipeline & pipeline) /// Preliminary LIMIT - is used in every source, if there are several sources, before they are combined. void InterpreterSelectQuery::executePreLimit(Pipeline & pipeline) { + const auto * query = query_ptr->As(); + /// If there is LIMIT - if (query.limit_length) + if (query->limit_length) { - auto [limit_length, limit_offset] = getLimitLengthAndOffset(query, context); + auto [limit_length, limit_offset] = getLimitLengthAndOffset(*query, context); pipeline.transform([&, limit = limit_length + limit_offset](auto & stream) { stream = std::make_shared(stream, limit, 0, false); @@ -1403,14 +1422,16 @@ void InterpreterSelectQuery::executePreLimit(Pipeline & pipeline) void InterpreterSelectQuery::executeLimitBy(Pipeline & pipeline) { - if (!query.limit_by_value || !query.limit_by_expression_list) + const auto * query = query_ptr->As(); + + if (!query->limit_by_value || !query->limit_by_expression_list) return; Names columns; - for (const auto & elem : query.limit_by_expression_list->children) + for (const auto & elem : query->limit_by_expression_list->children) columns.emplace_back(elem->getColumnName()); - UInt64 value = getLimitUIntValue(query.limit_by_value, context); + UInt64 value = getLimitUIntValue(query->limit_by_value, context); pipeline.transform([&](auto & stream) { @@ -1444,8 +1465,10 @@ bool hasWithTotalsInAnySubqueryInFromClause(const ASTSelectQuery & query) void InterpreterSelectQuery::executeLimit(Pipeline & pipeline) { + const auto * query = query_ptr->As(); + /// If there is LIMIT - if (query.limit_length) + if (query->limit_length) { /** Rare case: * if there is no WITH TOTALS and there is a subquery in FROM, and there is WITH TOTALS on one of the levels, @@ -1458,15 +1481,15 @@ void InterpreterSelectQuery::executeLimit(Pipeline & pipeline) */ bool always_read_till_end = false; - if (query.group_by_with_totals && !query.order_expression_list) + if (query->group_by_with_totals && !query->order_expression_list) always_read_till_end = true; - if (!query.group_by_with_totals && hasWithTotalsInAnySubqueryInFromClause(query)) + if (!query->group_by_with_totals && hasWithTotalsInAnySubqueryInFromClause(*query)) always_read_till_end = true; UInt64 limit_length; UInt64 limit_offset; - std::tie(limit_length, limit_offset) = getLimitLengthAndOffset(query, context); + std::tie(limit_length, limit_offset) = getLimitLengthAndOffset(*query, context); pipeline.transform([&](auto & stream) { @@ -1515,14 +1538,14 @@ void InterpreterSelectQuery::unifyStreams(Pipeline & pipeline) void InterpreterSelectQuery::ignoreWithTotals() { - query.group_by_with_totals = false; + query_ptr->As()->group_by_with_totals = false; } void InterpreterSelectQuery::initSettings() { - if (query.settings) - InterpreterSetQuery(query.settings, context).executeForCurrentContext(); + if (auto settings = query_ptr->As()->settings) + InterpreterSetQuery(settings, context).executeForCurrentContext(); } } diff --git a/dbms/src/Interpreters/InterpreterSelectQuery.h b/dbms/src/Interpreters/InterpreterSelectQuery.h index de5a11e727b..032f574c9a4 100644 --- a/dbms/src/Interpreters/InterpreterSelectQuery.h +++ b/dbms/src/Interpreters/InterpreterSelectQuery.h @@ -222,7 +222,6 @@ private: void initSettings(); ASTPtr query_ptr; - ASTSelectQuery & query; Context context; QueryProcessingStage::Enum to_stage; size_t subquery_depth = 0; diff --git a/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp b/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp index 852bf45d720..ed40035e5cc 100644 --- a/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp +++ b/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp @@ -42,21 +42,21 @@ Block InterpreterShowCreateQuery::getSampleBlock() BlockInputStreamPtr InterpreterShowCreateQuery::executeImpl() { - const auto & ast = dynamic_cast(*query_ptr); + const auto * ast = query_ptr->As(); - if (ast.temporary && !ast.database.empty()) + if (ast->temporary && !ast->database.empty()) throw Exception("Temporary databases are not possible.", ErrorCodes::SYNTAX_ERROR); ASTPtr create_query; - if (ast.temporary) - create_query = context.getCreateExternalTableQuery(ast.table); - else if (ast.table.empty()) - create_query = context.getCreateDatabaseQuery(ast.database); + if (ast->temporary) + create_query = context.getCreateExternalTableQuery(ast->table); + else if (ast->table.empty()) + create_query = context.getCreateDatabaseQuery(ast->database); else - create_query = context.getCreateTableQuery(ast.database, ast.table); + create_query = context.getCreateTableQuery(ast->database, ast->table); - if (!create_query && ast.temporary) - throw Exception("Unable to show the create query of " + ast.table + ". Maybe it was created by the system.", ErrorCodes::THERE_IS_NO_QUERY); + if (!create_query && ast->temporary) + throw Exception("Unable to show the create query of " + ast->table + ". Maybe it was created by the system.", ErrorCodes::THERE_IS_NO_QUERY); std::stringstream stream; formatAST(*create_query, stream, false, true); diff --git a/dbms/src/Interpreters/InterpreterSystemQuery.cpp b/dbms/src/Interpreters/InterpreterSystemQuery.cpp index e1233a04180..394569d44be 100644 --- a/dbms/src/Interpreters/InterpreterSystemQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSystemQuery.cpp @@ -117,7 +117,7 @@ InterpreterSystemQuery::InterpreterSystemQuery(const ASTPtr & query_ptr_, Contex BlockIO InterpreterSystemQuery::execute() { - auto & query = typeid_cast(*query_ptr); + auto * query = query_ptr->As(); using Type = ASTSystemQuery::Type; @@ -126,10 +126,10 @@ BlockIO InterpreterSystemQuery::execute() system_context.setSetting("profile", context.getSystemProfileName()); /// Make canonical query for simpler processing - if (!query.target_table.empty() && query.target_database.empty()) - query.target_database = context.getCurrentDatabase(); + if (!query->target_table.empty() && query->target_database.empty()) + query->target_database = context.getCurrentDatabase(); - switch (query.type) + switch (query->type) { case Type::SHUTDOWN: if (kill(0, SIGTERM)) @@ -156,7 +156,7 @@ BlockIO InterpreterSystemQuery::execute() break; #endif case Type::RELOAD_DICTIONARY: - system_context.getExternalDictionaries().reloadDictionary(query.target_dictionary); + system_context.getExternalDictionaries().reloadDictionary(query->target_dictionary); break; case Type::RELOAD_DICTIONARIES: executeCommandsAndThrowIfError( @@ -171,38 +171,38 @@ BlockIO InterpreterSystemQuery::execute() system_context.reloadConfig(); break; case Type::STOP_MERGES: - startStopAction(context, query, ActionLocks::PartsMerge, false); + startStopAction(context, *query, ActionLocks::PartsMerge, false); break; case Type::START_MERGES: - startStopAction(context, query, ActionLocks::PartsMerge, true); + startStopAction(context, *query, ActionLocks::PartsMerge, true); break; case Type::STOP_FETCHES: - startStopAction(context, query, ActionLocks::PartsFetch, false); + startStopAction(context, *query, ActionLocks::PartsFetch, false); break; case Type::START_FETCHES: - startStopAction(context, query, ActionLocks::PartsFetch, true); + startStopAction(context, *query, ActionLocks::PartsFetch, true); break; case Type::STOP_REPLICATED_SENDS: - startStopAction(context, query, ActionLocks::PartsSend, false); + startStopAction(context, *query, ActionLocks::PartsSend, false); break; case Type::START_REPLICATED_SENDS: - startStopAction(context, query, ActionLocks::PartsSend, true); + startStopAction(context, *query, ActionLocks::PartsSend, true); break; case Type::STOP_REPLICATION_QUEUES: - startStopAction(context, query, ActionLocks::ReplicationQueue, false); + startStopAction(context, *query, ActionLocks::ReplicationQueue, false); break; case Type::START_REPLICATION_QUEUES: - startStopAction(context, query, ActionLocks::ReplicationQueue, true); + startStopAction(context, *query, ActionLocks::ReplicationQueue, true); break; case Type::SYNC_REPLICA: - syncReplica(query); + syncReplica(*query); break; case Type::RESTART_REPLICAS: restartReplicas(system_context); break; case Type::RESTART_REPLICA: - if (!tryRestartReplica(query.target_database, query.target_table, system_context)) - throw Exception("There is no " + query.target_database + "." + query.target_table + " replicated table", + if (!tryRestartReplica(query->target_database, query->target_table, system_context)) + throw Exception("There is no " + query->target_database + "." + query->target_table + " replicated table", ErrorCodes::BAD_ARGUMENTS); break; case Type::FLUSH_LOGS: @@ -214,7 +214,7 @@ BlockIO InterpreterSystemQuery::execute() break; case Type::STOP_LISTEN_QUERIES: case Type::START_LISTEN_QUERIES: - throw Exception(String(ASTSystemQuery::typeToString(query.type)) + " is not supported yet", ErrorCodes::NOT_IMPLEMENTED); + throw Exception(String(ASTSystemQuery::typeToString(query->type)) + " is not supported yet", ErrorCodes::NOT_IMPLEMENTED); default: throw Exception("Unknown type of SYSTEM query", ErrorCodes::BAD_ARGUMENTS); } @@ -248,20 +248,20 @@ StoragePtr InterpreterSystemQuery::tryRestartReplica(const String & database_nam /// Attach actions { /// getCreateTableQuery must return canonical CREATE query representation, there are no need for AST postprocessing - auto & create = typeid_cast(*create_ast); - create.attach = true; + auto * create = create_ast->As(); + create->attach = true; std::string data_path = database->getDataPath(); - auto columns = InterpreterCreateQuery::getColumnsDescription(*create.columns_list->columns, system_context); + auto columns = InterpreterCreateQuery::getColumnsDescription(*create->columns_list->columns, system_context); - StoragePtr table = StorageFactory::instance().get(create, + StoragePtr table = StorageFactory::instance().get(*create, data_path, table_name, database_name, system_context, system_context.getGlobalContext(), columns, - create.attach, + create->attach, false); database->createTable(system_context, table_name, table, create_ast); diff --git a/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp b/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp index 36ce38853f5..5fd35270e5b 100644 --- a/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp +++ b/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp @@ -97,11 +97,10 @@ struct ColumnAliasesMatcher static void visit(ASTPtr & ast, Data & data) { - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) visit(*t, ast, data); - if (typeid_cast(ast.get()) || - typeid_cast(ast.get())) + if (ast->As() || ast->As()) throw Exception("Multiple JOIN do not support asterisks yet", ErrorCodes::NOT_IMPLEMENTED); } @@ -160,9 +159,9 @@ struct AppendSemanticVisitorData for (auto & child : select.select_expression_list->children) { - if (auto * node = typeid_cast(child.get())) + if (auto * node = child->As()) AsteriskSemantic::setAliases(*node, rev_aliases); - if (auto * node = typeid_cast(child.get())) + if (auto * node = child->As()) AsteriskSemantic::setAliases(*node, rev_aliases); } @@ -233,7 +232,7 @@ using AppendSemanticVisitor = InDepthNodeVisitor; void JoinToSubqueryTransformMatcher::visit(ASTPtr & ast, Data & data) { - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) visit(*t, ast, data); } @@ -261,10 +260,10 @@ void JoinToSubqueryTransformMatcher::visit(ASTSelectQuery & select, ASTPtr &, Da /// JOIN sections for (auto & child : select.tables->children) { - auto table = typeid_cast(child.get()); + auto * table = child->As(); if (table->table_join) { - auto * join = typeid_cast(table->table_join.get()); + auto * join = table->table_join->As(); ColumnAliasesVisitor(aliases_data).visit(join->on_expression); } } diff --git a/dbms/src/Interpreters/LogicalExpressionsOptimizer.cpp b/dbms/src/Interpreters/LogicalExpressionsOptimizer.cpp index d7f04ff2a25..27a80242d96 100644 --- a/dbms/src/Interpreters/LogicalExpressionsOptimizer.cpp +++ b/dbms/src/Interpreters/LogicalExpressionsOptimizer.cpp @@ -19,7 +19,7 @@ namespace ErrorCodes } -LogicalExpressionsOptimizer::OrWithExpression::OrWithExpression(ASTFunction * or_function_, +LogicalExpressionsOptimizer::OrWithExpression::OrWithExpression(const ASTFunction * or_function_, const IAST::Hash & expression_, const std::string & alias_) : or_function(or_function_), expression(expression_), alias(alias_) { @@ -111,24 +111,24 @@ void LogicalExpressionsOptimizer::collectDisjunctiveEqualityChains() bool found_chain = false; - auto function = typeid_cast(to_node); - if ((function != nullptr) && (function->name == "or") && (function->children.size() == 1)) + auto * function = to_node->As(); + if (function && function->name == "or" && function->children.size() == 1) { - auto expression_list = typeid_cast(&*(function->children[0])); - if (expression_list != nullptr) + const auto * expression_list = function->children[0]->As(); + if (expression_list) { /// The chain of elements of the OR expression. for (auto & child : expression_list->children) { - auto equals = typeid_cast(&*child); - if ((equals != nullptr) && (equals->name == "equals") && (equals->children.size() == 1)) + auto * equals = child->As(); + if (equals && equals->name == "equals" && equals->children.size() == 1) { - auto equals_expression_list = typeid_cast(&*(equals->children[0])); - if ((equals_expression_list != nullptr) && (equals_expression_list->children.size() == 2)) + const auto * equals_expression_list = equals->children[0]->As(); + if (equals_expression_list && equals_expression_list->children.size() == 2) { /// Equality expr = xN. - auto literal = typeid_cast(&*(equals_expression_list->children[1])); - if (literal != nullptr) + const auto * literal = equals_expression_list->children[1]->As(); + if (literal) { auto expr_lhs = equals_expression_list->children[0]->getTreeHash(); OrWithExpression or_with_expression{function, expr_lhs, function->tryGetAlias()}; @@ -157,7 +157,7 @@ void LogicalExpressionsOptimizer::collectDisjunctiveEqualityChains() { for (auto & child : to_node->children) { - if (typeid_cast(child.get()) == nullptr) + if (!child->As()) { if (!visited_nodes.count(child.get())) to_visit.push_back(Edge(to_node, &*child)); @@ -187,10 +187,9 @@ void LogicalExpressionsOptimizer::collectDisjunctiveEqualityChains() namespace { -inline ASTs & getFunctionOperands(ASTFunction * or_function) +inline ASTs & getFunctionOperands(const ASTFunction * or_function) { - auto expression_list = static_cast(&*(or_function->children[0])); - return expression_list->children; + return or_function->children[0]->children; } } @@ -206,11 +205,11 @@ bool LogicalExpressionsOptimizer::mayOptimizeDisjunctiveEqualityChain(const Disj /// We check that the right-hand sides of all equalities have the same type. auto & first_operands = getFunctionOperands(equality_functions[0]); - auto first_literal = static_cast(&*first_operands[1]); + const auto * first_literal = first_operands[1]->As(); for (size_t i = 1; i < equality_functions.size(); ++i) { auto & operands = getFunctionOperands(equality_functions[i]); - auto literal = static_cast(&*operands[1]); + const auto * literal = operands[1]->As(); if (literal->value.getType() != first_literal->value.getType()) return false; @@ -238,8 +237,8 @@ void LogicalExpressionsOptimizer::addInExpression(const DisjunctiveEqualityChain /// Otherwise, they would be specified in the order of the ASTLiteral addresses, which is nondeterministic. std::sort(value_list->children.begin(), value_list->children.end(), [](const DB::ASTPtr & lhs, const DB::ASTPtr & rhs) { - const auto val_lhs = static_cast(&*lhs); - const auto val_rhs = static_cast(&*rhs); + const auto * val_lhs = lhs->As(); + const auto * val_rhs = rhs->As(); return val_lhs->value < val_rhs->value; }); @@ -277,7 +276,7 @@ void LogicalExpressionsOptimizer::cleanupOrExpressions() { /// Saves for each optimized OR-chain the iterator on the first element /// list of operands to be deleted. - std::unordered_map garbage_map; + std::unordered_map garbage_map; /// Initialization. garbage_map.reserve(processed_count); diff --git a/dbms/src/Interpreters/LogicalExpressionsOptimizer.h b/dbms/src/Interpreters/LogicalExpressionsOptimizer.h index 636c83e1d9f..09c3931ce1d 100644 --- a/dbms/src/Interpreters/LogicalExpressionsOptimizer.h +++ b/dbms/src/Interpreters/LogicalExpressionsOptimizer.h @@ -51,11 +51,10 @@ private: */ struct OrWithExpression { - OrWithExpression(ASTFunction * or_function_, const IAST::Hash & expression_, - const std::string & alias_); + OrWithExpression(const ASTFunction * or_function_, const IAST::Hash & expression_, const std::string & alias_); bool operator<(const OrWithExpression & rhs) const; - ASTFunction * or_function; + const ASTFunction * or_function; const IAST::Hash expression; const std::string alias; }; @@ -95,8 +94,8 @@ private: private: using ParentNodes = std::vector; - using FunctionParentMap = std::unordered_map; - using ColumnToPosition = std::unordered_map; + using FunctionParentMap = std::unordered_map; + using ColumnToPosition = std::unordered_map; private: ASTSelectQuery * select_query; diff --git a/dbms/src/Interpreters/OptimizeIfWithConstantConditionVisitor.cpp b/dbms/src/Interpreters/OptimizeIfWithConstantConditionVisitor.cpp index e73a734ab16..26d62fe8bf3 100644 --- a/dbms/src/Interpreters/OptimizeIfWithConstantConditionVisitor.cpp +++ b/dbms/src/Interpreters/OptimizeIfWithConstantConditionVisitor.cpp @@ -16,7 +16,7 @@ namespace ErrorCodes static bool tryExtractConstValueFromCondition(const ASTPtr & condition, bool & value) { /// numeric constant in condition - if (const ASTLiteral * literal = typeid_cast(condition.get())) + if (const auto * literal = condition->As()) { if (literal->value.getType() == Field::Types::Int64 || literal->value.getType() == Field::Types::UInt64) @@ -27,14 +27,14 @@ static bool tryExtractConstValueFromCondition(const ASTPtr & condition, bool & v } /// cast of numeric constant in condition to UInt8 - if (const ASTFunction * function = typeid_cast(condition.get())) + if (const auto * function = condition->As()) { if (function->name == "CAST") { - if (ASTExpressionList * expr_list = typeid_cast(function->arguments.get())) + if (const auto * expr_list = function->arguments->As()) { const ASTPtr & type_ast = expr_list->children.at(1); - if (const ASTLiteral * type_literal = typeid_cast(type_ast.get())) + if (const auto * type_literal = type_ast->As()) { if (type_literal->value.getType() == Field::Types::String && type_literal->value.get() == "UInt8") @@ -54,7 +54,7 @@ void OptimizeIfWithConstantConditionVisitor::visit(ASTPtr & current_ast) for (ASTPtr & child : current_ast->children) { - auto * function_node = typeid_cast(child.get()); + auto * function_node = child->As(); if (!function_node || function_node->name != "if") { visit(child); @@ -62,7 +62,7 @@ void OptimizeIfWithConstantConditionVisitor::visit(ASTPtr & current_ast) } visit(function_node->arguments); - auto * args = typeid_cast(function_node->arguments.get()); + const auto * args = function_node->arguments->As(); if (args->children.size() != 3) throw Exception("Wrong number of arguments for function 'if' (" + toString(args->children.size()) + " instead of 3)", diff --git a/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp b/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp index 85c34bc4563..d6d3e4d0194 100644 --- a/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp +++ b/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp @@ -151,7 +151,7 @@ std::vector PredicateExpressionsOptimizer::splitConjunctionPredicate(AST { const auto expression = predicate_expressions.at(idx); - if (const auto function = typeid_cast(expression.get())) + if (const auto * function = expression->As()) { if (function->name == and_function_name) { @@ -260,7 +260,7 @@ void PredicateExpressionsOptimizer::setNewAliasesForInnerPredicate( bool PredicateExpressionsOptimizer::isArrayJoinFunction(const ASTPtr & node) { - if (auto function = typeid_cast(node.get())) + if (const auto * function = node->As()) { if (function->name == "arrayJoin") return true; @@ -309,7 +309,7 @@ void PredicateExpressionsOptimizer::getSubqueryProjectionColumns(const ASTPtr & const ASTPtr & subselect = subquery->children[0]; ASTs select_with_union_projections; - auto select_with_union_query = static_cast(subselect.get()); + const auto * select_with_union_query = subselect->As(); for (auto & select : select_with_union_query->list_of_selects->children) { @@ -325,7 +325,7 @@ void PredicateExpressionsOptimizer::getSubqueryProjectionColumns(const ASTPtr & subquery_projections.emplace_back(std::pair(select_projection_columns[i], qualified_name_prefix + select_with_union_projections[i]->getAliasOrColumnName())); - projection_columns.insert(std::pair(static_cast(select.get()), subquery_projections)); + projection_columns.insert(std::pair(select->As(), subquery_projections)); } } } @@ -333,7 +333,7 @@ void PredicateExpressionsOptimizer::getSubqueryProjectionColumns(const ASTPtr & ASTs PredicateExpressionsOptimizer::getSelectQueryProjectionColumns(ASTPtr & ast) { ASTs projection_columns; - auto select_query = static_cast(ast.get()); + auto * select_query = ast->As(); /// first should normalize query tree. std::unordered_map aliases; @@ -352,7 +352,7 @@ ASTs PredicateExpressionsOptimizer::getSelectQueryProjectionColumns(ASTPtr & ast for (const auto & projection_column : select_query->select_expression_list->children) { - if (typeid_cast(projection_column.get()) || typeid_cast(projection_column.get())) + if (projection_column->As() || projection_column->As()) { ASTs evaluated_columns = evaluateAsterisk(select_query, projection_column); @@ -375,7 +375,7 @@ ASTs PredicateExpressionsOptimizer::evaluateAsterisk(ASTSelectQuery * select_que std::vector tables_expression = getSelectTablesExpression(*select_query); - if (const auto qualified_asterisk = typeid_cast(asterisk.get())) + if (const auto * qualified_asterisk = asterisk->As()) { if (qualified_asterisk->children.size() != 1) throw Exception("Logical error: qualified asterisk must have exactly one child", ErrorCodes::LOGICAL_ERROR); @@ -399,8 +399,8 @@ ASTs PredicateExpressionsOptimizer::evaluateAsterisk(ASTSelectQuery * select_que { if (table_expression->subquery) { - const auto subquery = static_cast(table_expression->subquery.get()); - const auto select_with_union_query = static_cast(subquery->children[0].get()); + const auto * subquery = table_expression->subquery->As(); + const auto * select_with_union_query = subquery->children[0]->As(); const auto subquery_projections = getSelectQueryProjectionColumns(select_with_union_query->list_of_selects->children[0]); projection_columns.insert(projection_columns.end(), subquery_projections.begin(), subquery_projections.end()); } @@ -415,7 +415,7 @@ ASTs PredicateExpressionsOptimizer::evaluateAsterisk(ASTSelectQuery * select_que } else if (table_expression->database_and_table_name) { - const auto database_and_table_ast = static_cast(table_expression->database_and_table_name.get()); + const auto * database_and_table_ast = table_expression->database_and_table_name->As(); DatabaseAndTableWithAlias database_and_table_name(*database_and_table_ast); storage = context.getTable(database_and_table_name.database, database_and_table_name.table); } diff --git a/dbms/src/Interpreters/QueryAliasesVisitor.cpp b/dbms/src/Interpreters/QueryAliasesVisitor.cpp index 96ef4806676..aed03d52a08 100644 --- a/dbms/src/Interpreters/QueryAliasesVisitor.cpp +++ b/dbms/src/Interpreters/QueryAliasesVisitor.cpp @@ -32,18 +32,16 @@ static String wrongAliasMessage(const ASTPtr & ast, const ASTPtr & prev_ast, con bool QueryAliasesMatcher::needChildVisit(ASTPtr & node, const ASTPtr &) { /// Don't descent into table functions and subqueries and special case for ArrayJoin. - if (typeid_cast(node.get()) || - typeid_cast(node.get()) || - typeid_cast(node.get())) + if (node->As() || node->As() || node->As()) return false; return true; } void QueryAliasesMatcher::visit(ASTPtr & ast, Data & data) { - if (auto * s = typeid_cast(ast.get())) + if (auto * s = ast->As()) visit(*s, ast, data); - else if (auto * aj = typeid_cast(ast.get())) + else if (auto * aj = ast->As()) visit(*aj, ast, data); else visitOther(ast, data); diff --git a/dbms/src/Interpreters/QueryNormalizer.cpp b/dbms/src/Interpreters/QueryNormalizer.cpp index 6722734d76c..430a0fdd6b0 100644 --- a/dbms/src/Interpreters/QueryNormalizer.cpp +++ b/dbms/src/Interpreters/QueryNormalizer.cpp @@ -134,16 +134,16 @@ void QueryNormalizer::visit(ASTTablesInSelectQueryElement & node, const ASTPtr & /// mark table Identifiers as 'not a column' if (node.table_expression) { - auto & expr = static_cast(*node.table_expression); - setIdentifierSpecial(expr.database_and_table_name); + auto * expr = node.table_expression->As(); + setIdentifierSpecial(expr->database_and_table_name); } /// normalize JOIN ON section if (node.table_join) { - auto & join = static_cast(*node.table_join); - if (join.on_expression) - visit(join.on_expression, data); + auto * join = node.table_join->As(); + if (join->on_expression) + visit(join->on_expression, data); } } @@ -177,7 +177,7 @@ void QueryNormalizer::visit(ASTSelectQuery & select, const ASTPtr & ast, Data & /// on aliases in expressions of the form 123 AS x, arrayMap(x -> 1, [2]). void QueryNormalizer::visitChildren(const ASTPtr & node, Data & data) { - if (ASTFunction * func_node = typeid_cast(node.get())) + if (const auto * func_node = node->As()) { /// We skip the first argument. We also assume that the lambda function can not have parameters. size_t first_pos = 0; @@ -194,7 +194,7 @@ void QueryNormalizer::visitChildren(const ASTPtr & node, Data & data) visit(child, data); } } - else if (!typeid_cast(node.get())) + else if (!node->As()) { for (auto & child : node->children) if (needVisitChild(child)) @@ -225,13 +225,13 @@ void QueryNormalizer::visit(ASTPtr & ast, Data & data) data.current_alias = my_alias; } - if (auto * node = typeid_cast(ast.get())) + if (auto * node = ast->As()) visit(*node, ast, data); - if (auto * node = typeid_cast(ast.get())) + if (auto * node = ast->As()) visit(*node, ast, data); - if (auto * node = typeid_cast(ast.get())) + if (auto * node = ast->As()) visit(*node, ast, data); - if (auto * node = typeid_cast(ast.get())) + if (auto * node = ast->As()) visit(*node, ast, data); /// If we replace the root of the subtree, we will be called again for the new root, in case the alias is replaced by an alias. diff --git a/dbms/src/Interpreters/RequiredSourceColumnsVisitor.cpp b/dbms/src/Interpreters/RequiredSourceColumnsVisitor.cpp index 8c24c916f22..846196728da 100644 --- a/dbms/src/Interpreters/RequiredSourceColumnsVisitor.cpp +++ b/dbms/src/Interpreters/RequiredSourceColumnsVisitor.cpp @@ -22,7 +22,7 @@ static std::vector extractNamesFromLambda(const ASTFunction & node) if (node.arguments->children.size() != 2) throw Exception("lambda requires two arguments", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - ASTFunction * lambda_args_tuple = typeid_cast(node.arguments->children[0].get()); + const auto * lambda_args_tuple = node.arguments->children[0]->As(); if (!lambda_args_tuple || lambda_args_tuple->name != "tuple") throw Exception("First argument of lambda must be a tuple", ErrorCodes::TYPE_MISMATCH); @@ -30,7 +30,7 @@ static std::vector extractNamesFromLambda(const ASTFunction & node) std::vector names; for (auto & child : lambda_args_tuple->arguments->children) { - ASTIdentifier * identifier = typeid_cast(child.get()); + const auto * identifier = child->As(); if (!identifier) throw Exception("lambda argument declarations must be identifiers", ErrorCodes::TYPE_MISMATCH); @@ -42,16 +42,14 @@ static std::vector extractNamesFromLambda(const ASTFunction & node) bool RequiredSourceColumnsMatcher::needChildVisit(ASTPtr & node, const ASTPtr & child) { - if (typeid_cast(child.get())) + if (child->As()) return false; /// Processed. Do not need children. - if (typeid_cast(node.get()) || - typeid_cast(node.get()) || - typeid_cast(node.get())) + if (node->As() || node->As() || node->As()) return false; - if (auto * f = typeid_cast(node.get())) + if (const auto * f = node->As()) { /// "indexHint" is a special function for index analysis. Everything that is inside it is not calculated. @sa KeyCondition /// "lambda" visit children itself. @@ -66,12 +64,12 @@ void RequiredSourceColumnsMatcher::visit(ASTPtr & ast, Data & data) { /// results are columns - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) { visit(*t, ast, data); return; } - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) { data.addColumnAliasIfAny(*ast); visit(*t, ast, data); @@ -80,24 +78,24 @@ void RequiredSourceColumnsMatcher::visit(ASTPtr & ast, Data & data) /// results are tables - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) { visit(*t, ast, data); return; } - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) { visit(*t, ast, data); return; } - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) { data.addTableAliasIfAny(*ast); visit(*t, ast, data); return; } - if (typeid_cast(ast.get())) + if (ast->As()) { data.addTableAliasIfAny(*ast); return; @@ -105,7 +103,7 @@ void RequiredSourceColumnsMatcher::visit(ASTPtr & ast, Data & data) /// other - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) { data.has_array_join = true; visit(*t, ast, data); @@ -118,7 +116,7 @@ void RequiredSourceColumnsMatcher::visit(ASTSelectQuery & select, const ASTPtr & /// special case for top-level SELECT items: they are publics for (auto & node : select.select_expression_list->children) { - if (auto * identifier = typeid_cast(node.get())) + if (const auto * identifier = node->As()) data.addColumnIdentifier(*identifier); else data.addColumnAliasIfAny(*node); @@ -170,9 +168,9 @@ void RequiredSourceColumnsMatcher::visit(ASTTablesInSelectQueryElement & node, c for (auto & child : node.children) { - if (auto * e = typeid_cast(child.get())) + if (auto * e = child->As()) expr = e; - if (auto * j = typeid_cast(child.get())) + if (auto * j = child->As()) join = j; } @@ -207,7 +205,7 @@ void RequiredSourceColumnsMatcher::visit(const ASTArrayJoin & node, const ASTPtr { data.addArrayJoinAliasIfAny(*expr); - if (auto * identifier = typeid_cast(expr.get())) + if (const auto * identifier = expr->As()) { data.addArrayJoinIdentifier(*identifier); continue; diff --git a/dbms/src/Interpreters/Set.cpp b/dbms/src/Interpreters/Set.cpp index a10d520d779..2a8d52ec2d9 100644 --- a/dbms/src/Interpreters/Set.cpp +++ b/dbms/src/Interpreters/Set.cpp @@ -205,13 +205,13 @@ bool Set::insertFromBlock(const Block & block) } -static Field extractValueFromNode(ASTPtr & node, const IDataType & type, const Context & context) +static Field extractValueFromNode(const ASTPtr & node, const IDataType & type, const Context & context) { - if (ASTLiteral * lit = typeid_cast(node.get())) + if (const auto * lit = node->As()) { return convertFieldToType(lit->value, type); } - else if (typeid_cast(node.get())) + else if (node->As()) { std::pair value_raw = evaluateConstantExpression(node, context); return convertFieldToType(value_raw.first, type, value_raw.second.get()); @@ -235,8 +235,8 @@ void Set::createFromAST(const DataTypes & types, ASTPtr node, const Context & co DataTypePtr tuple_type; Row tuple_values; - ASTExpressionList & list = typeid_cast(*node); - for (auto & elem : list.children) + const auto * list = node->As(); + for (auto & elem : list->children) { if (num_columns == 1) { @@ -245,7 +245,7 @@ void Set::createFromAST(const DataTypes & types, ASTPtr node, const Context & co if (!value.isNull()) columns[0]->insert(value); } - else if (ASTFunction * func = typeid_cast(elem.get())) + else if (const auto * func = elem->As()) { Field function_result; const TupleBackend * tuple = nullptr; diff --git a/dbms/src/Interpreters/SyntaxAnalyzer.cpp b/dbms/src/Interpreters/SyntaxAnalyzer.cpp index 2c9496ceec4..a2342ee5587 100644 --- a/dbms/src/Interpreters/SyntaxAnalyzer.cpp +++ b/dbms/src/Interpreters/SyntaxAnalyzer.cpp @@ -63,7 +63,7 @@ using LogAST = DebugASTLog; /// set to true to enable logs /// Add columns from storage to source_columns list. -void collectSourceColumns(ASTSelectQuery * select_query, StoragePtr storage, NamesAndTypesList & source_columns) +void collectSourceColumns(const ASTSelectQuery * select_query, StoragePtr storage, NamesAndTypesList & source_columns) { if (storage) { @@ -232,7 +232,7 @@ void optimizeGroupBy(ASTSelectQuery * select_query, const NameSet & source_colum /// iterate over each GROUP BY expression, eliminate injective function calls and literals for (size_t i = 0; i < group_exprs.size();) { - if (const auto function = typeid_cast(group_exprs[i].get())) + if (const auto * function = group_exprs[i]->As()) { /// assert function is injective if (possibly_injective_function_names.count(function->name)) @@ -359,11 +359,11 @@ void optimizeLimitBy(const ASTSelectQuery * select_query) /// Remove duplicated columns from USING(...). void optimizeUsing(const ASTSelectQuery * select_query) { - auto node = const_cast(select_query->join()); + const auto * node = select_query->join()->As(); if (!node) return; - auto table_join = static_cast(&*node->table_join); + const auto * table_join = node->table_join->As(); if (!(table_join && table_join->using_expression_list)) return; @@ -406,7 +406,7 @@ void getArrayJoinedColumns(ASTPtr & query, SyntaxAnalyzerResult & result, const String result_name = expr->getAliasOrColumnName(); /// This is an array. - if (!isIdentifier(expr) || source_columns_set.count(source_name)) + if (!expr->As() || source_columns_set.count(source_name)) { result.array_join_result_to_source[result_name] = source_name; } @@ -552,24 +552,24 @@ void collectJoinedColumns(AnalyzedJoin & analyzed_join, const ASTSelectQuery & s if (!node) return; - const auto & table_join = static_cast(*node->table_join); - const auto & table_expression = static_cast(*node->table_expression); - DatabaseAndTableWithAlias joined_table_name(table_expression, current_database); + const auto * table_join = node->table_join->As(); + const auto * table_expression = node->table_expression->As(); + DatabaseAndTableWithAlias joined_table_name(*table_expression, current_database); - if (table_join.using_expression_list) + if (table_join->using_expression_list) { - auto & keys = typeid_cast(*table_join.using_expression_list); - for (const auto & key : keys.children) + const auto * keys = table_join->using_expression_list->As(); + for (const auto & key : keys->children) analyzed_join.addUsingKey(key); for (auto & name : analyzed_join.key_names_right) if (source_columns.count(name)) name = joined_table_name.getQualifiedNamePrefix() + name; } - else if (table_join.on_expression) - collectJoinedColumnsFromJoinOnExpr(analyzed_join, table_join); + else if (table_join->on_expression) + collectJoinedColumnsFromJoinOnExpr(analyzed_join, *table_join); - bool make_nullable = join_use_nulls && (table_join.kind == ASTTableJoin::Kind::Left || table_join.kind == ASTTableJoin::Kind::Full); + bool make_nullable = join_use_nulls && (table_join->kind == ASTTableJoin::Kind::Left || table_join->kind == ASTTableJoin::Kind::Full); analyzed_join.calculateAvailableJoinedColumns(make_nullable); } @@ -594,19 +594,19 @@ void replaceJoinedTable(const ASTTablesInSelectQueryElement* join) if (!join || !join->table_expression) return; - auto & table_expr = static_cast(*join->table_expression.get()); - if (table_expr.database_and_table_name) + const auto * table_expr = join->table_expression->As(); + if (table_expr->database_and_table_name) { - auto & table_id = typeid_cast(*table_expr.database_and_table_name.get()); - String expr = "(select * from " + table_id.name + ") as " + table_id.shortName(); + const auto * table_id = table_expr->database_and_table_name->As(); + String expr = "(select * from " + table_id->name + ") as " + table_id->shortName(); // FIXME: since the expression "a as b" exposes both "a" and "b" names, which is not equivalent to "(select * from a) as b", // we can't replace aliased tables. // FIXME: long table names include database name, which we can't save within alias. - if (table_id.alias.empty() && table_id.isShort()) + if (table_id->alias.empty() && table_id->isShort()) { ParserTableExpression parser; - table_expr = static_cast(*parseQuery(parser, expr, 0)); + table_expr = parseQuery(parser, expr, 0)->As(); } } } @@ -620,7 +620,7 @@ SyntaxAnalyzerResultPtr SyntaxAnalyzer::analyze( const Names & required_result_columns, StoragePtr storage) const { - auto * select_query = typeid_cast(query.get()); + auto * select_query = query->As(); if (!storage && select_query) { if (auto db_and_table = getDatabaseAndTable(*select_query, 0)) @@ -651,10 +651,10 @@ SyntaxAnalyzerResultPtr SyntaxAnalyzer::analyze( if (settings.enable_optimize_predicate_expression) replaceJoinedTable(node); - const auto & joined_expression = static_cast(*node->table_expression); - DatabaseAndTableWithAlias table(joined_expression, context.getCurrentDatabase()); + const auto * joined_expression = node->table_expression->As(); + DatabaseAndTableWithAlias table(*joined_expression, context.getCurrentDatabase()); - NamesAndTypesList joined_columns = getNamesAndTypeListFromTableExpression(joined_expression, context); + NamesAndTypesList joined_columns = getNamesAndTypeListFromTableExpression(*joined_expression, context); Names original_names = qualifyOccupiedNames(joined_columns, source_columns_set, table); result.analyzed_join.calculateColumnsFromJoinedTable(joined_columns, original_names); } diff --git a/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp b/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp index 40948a6840f..54f3455f14a 100644 --- a/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp +++ b/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp @@ -31,13 +31,11 @@ namespace ErrorCodes bool TranslateQualifiedNamesMatcher::needChildVisit(ASTPtr & node, const ASTPtr & child) { /// Do not go to FROM, JOIN, subqueries. - if (typeid_cast(child.get()) || - typeid_cast(child.get())) + if (child->As() || child->As()) return false; /// Processed nodes. Do not go into children. - if (typeid_cast(node.get()) || - typeid_cast(node.get())) + if (node->As() || node->As()) return false; /// ASTSelectQuery + others @@ -46,15 +44,15 @@ bool TranslateQualifiedNamesMatcher::needChildVisit(ASTPtr & node, const ASTPtr void TranslateQualifiedNamesMatcher::visit(ASTPtr & ast, Data & data) { - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) visit(*t, ast, data); - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) visit(*t, ast, data); - if (auto * t = typeid_cast(ast.get())) + if (auto * t = ast->As()) visit(*t, ast, data); - if (auto * node = typeid_cast(ast.get())) + if (auto * node = ast->As()) visit(*node, ast, data); - if (auto * node = typeid_cast(ast.get())) + if (auto * node = ast->As()) visit(*node, ast, data); } @@ -243,8 +241,8 @@ void TranslateQualifiedNamesMatcher::extractJoinUsingColumns(const ASTPtr ast, D if (table_join->using_expression_list) { - auto & keys = typeid_cast(*table_join->using_expression_list); - for (const auto & key : keys.children) + const auto * keys = table_join->using_expression_list->As(); + for (const auto & key : keys->children) if (auto opt_column = getIdentifierName(key)) data.join_using_columns.insert(*opt_column); else if (key->As()) diff --git a/dbms/src/Interpreters/evaluateConstantExpression.cpp b/dbms/src/Interpreters/evaluateConstantExpression.cpp index 534d046fb70..23030fed191 100644 --- a/dbms/src/Interpreters/evaluateConstantExpression.cpp +++ b/dbms/src/Interpreters/evaluateConstantExpression.cpp @@ -64,7 +64,7 @@ ASTPtr evaluateConstantExpressionAsLiteral(const ASTPtr & node, const Context & return node; /// Branch with TableFunction in query. - if (auto table_func_ptr = typeid_cast(node.get())) + if (const auto * table_func_ptr = node->As()) if (TableFunctionFactory::instance().isTableFunctionName(table_func_ptr->name)) return node; diff --git a/dbms/src/Interpreters/executeQuery.cpp b/dbms/src/Interpreters/executeQuery.cpp index 95d373cb3fa..adcfa1a0f17 100644 --- a/dbms/src/Interpreters/executeQuery.cpp +++ b/dbms/src/Interpreters/executeQuery.cpp @@ -171,7 +171,7 @@ static std::tuple executeQueryImpl( /// TODO Parser should fail early when max_query_size limit is reached. ast = parseQuery(parser, begin, end, "", max_query_size); - auto * insert_query = dynamic_cast(ast.get()); + auto * insert_query = ast->As(); if (insert_query && insert_query->data) { query_end = insert_query->data; @@ -506,7 +506,7 @@ void executeQuery( if (streams.in) { - const ASTQueryWithOutput * ast_query_with_output = dynamic_cast(ast.get()); + const auto * ast_query_with_output = ast->As(); WriteBuffer * out_buf = &ostr; std::optional out_file_buf; diff --git a/dbms/src/Interpreters/interpretSubquery.cpp b/dbms/src/Interpreters/interpretSubquery.cpp index 76f075f2db3..bd5443cffeb 100644 --- a/dbms/src/Interpreters/interpretSubquery.cpp +++ b/dbms/src/Interpreters/interpretSubquery.cpp @@ -65,7 +65,7 @@ std::shared_ptr interpretSubquery( auto query_context = const_cast(&context.getQueryContext()); const auto & storage = query_context->executeTableFunction(table_expression); columns = storage->getColumns().ordinary; - select_query->addTableFunction(*const_cast(&table_expression)); + select_query->addTableFunction(*const_cast(&table_expression)); // XXX: const_cast should be avoided! } else { @@ -94,9 +94,9 @@ std::shared_ptr interpretSubquery( std::set all_column_names; std::set assigned_column_names; - if (ASTSelectWithUnionQuery * select_with_union = typeid_cast(query.get())) + if (const auto * select_with_union = query->As()) { - if (ASTSelectQuery * select = typeid_cast(select_with_union->list_of_selects->children.at(0).get())) + if (const auto * select = select_with_union->list_of_selects->children.at(0)->As()) { for (auto & expr : select->select_expression_list->children) all_column_names.insert(expr->getAliasOrColumnName()); diff --git a/dbms/src/Interpreters/loadMetadata.cpp b/dbms/src/Interpreters/loadMetadata.cpp index 2a94a6d2ff1..fcec49141d0 100644 --- a/dbms/src/Interpreters/loadMetadata.cpp +++ b/dbms/src/Interpreters/loadMetadata.cpp @@ -39,9 +39,9 @@ static void executeCreateQuery( ParserCreateQuery parser; ASTPtr ast = parseQuery(parser, query.data(), query.data() + query.size(), "in file " + file_name, 0); - ASTCreateQuery & ast_create_query = typeid_cast(*ast); - ast_create_query.attach = true; - ast_create_query.database = database; + auto * ast_create_query = ast->As(); + ast_create_query->attach = true; + ast_create_query->database = database; InterpreterCreateQuery interpreter(ast, context); interpreter.setInternal(true); diff --git a/dbms/src/Parsers/ASTAlterQuery.h b/dbms/src/Parsers/ASTAlterQuery.h index 2c77e2031de..d36d9694155 100644 --- a/dbms/src/Parsers/ASTAlterQuery.h +++ b/dbms/src/Parsers/ASTAlterQuery.h @@ -123,7 +123,7 @@ public: void add(const ASTPtr & command) { - commands.push_back(static_cast(command.get())); + commands.push_back(command->As()); children.push_back(command); } diff --git a/dbms/src/Parsers/ASTFunction.cpp b/dbms/src/Parsers/ASTFunction.cpp index 5048e62c5de..96d075ec5fe 100644 --- a/dbms/src/Parsers/ASTFunction.cpp +++ b/dbms/src/Parsers/ASTFunction.cpp @@ -62,7 +62,7 @@ ASTPtr ASTFunction::clone() const */ static bool highlightStringLiteralWithMetacharacters(const ASTPtr & node, const IAST::FormatSettings & settings, const char * metacharacters) { - if (auto literal = dynamic_cast(node.get())) + if (const auto * literal = node->As()) { if (literal->value.getType() == Field::Types::String) { diff --git a/dbms/src/Parsers/ASTIdentifier.cpp b/dbms/src/Parsers/ASTIdentifier.cpp index 2844963fd05..19d076d815f 100644 --- a/dbms/src/Parsers/ASTIdentifier.cpp +++ b/dbms/src/Parsers/ASTIdentifier.cpp @@ -83,13 +83,6 @@ ASTPtr createTableIdentifier(const String & database_name, const String & table_ return database_and_table; } -bool isIdentifier(const IAST * const ast) -{ - if (ast) - return ast->As(); - return false; -} - std::optional getIdentifierName(const IAST * const ast) { if (ast) @@ -112,7 +105,7 @@ bool getIdentifierName(const ASTPtr & ast, String & name) void setIdentifierSpecial(ASTPtr & ast) { if (ast) - if (ASTIdentifier * id = typeid_cast(ast.get())) + if (auto * id = ast->As()) id->semantic->special = true; } diff --git a/dbms/src/Parsers/ASTIdentifier.h b/dbms/src/Parsers/ASTIdentifier.h index 1439ab2dcbd..434f84eb77e 100644 --- a/dbms/src/Parsers/ASTIdentifier.h +++ b/dbms/src/Parsers/ASTIdentifier.h @@ -69,9 +69,6 @@ private: ASTPtr createTableIdentifier(const String & database_name, const String & table_name); void setIdentifierSpecial(ASTPtr & ast); -bool isIdentifier(const IAST * const ast); -inline bool isIdentifier(const ASTPtr & ast) { return isIdentifier(ast.get()); } - std::optional getIdentifierName(const IAST * const ast); inline std::optional getIdentifierName(const ASTPtr & ast) { return getIdentifierName(ast.get()); } bool getIdentifierName(const ASTPtr & ast, String & name); diff --git a/dbms/src/Parsers/ASTQueryWithOutput.cpp b/dbms/src/Parsers/ASTQueryWithOutput.cpp index c28b15cb8c1..22d3c8bcc30 100644 --- a/dbms/src/Parsers/ASTQueryWithOutput.cpp +++ b/dbms/src/Parsers/ASTQueryWithOutput.cpp @@ -49,7 +49,7 @@ void ASTQueryWithOutput::formatImpl(const FormatSettings & s, FormatState & stat bool ASTQueryWithOutput::resetOutputASTIfExist(IAST & ast) { - if (auto ast_with_output = dynamic_cast(&ast)) + if (auto * ast_with_output = ast.As()) { ast_with_output->format.reset(); ast_with_output->out_file.reset(); diff --git a/dbms/src/Parsers/ASTRenameQuery.h b/dbms/src/Parsers/ASTRenameQuery.h index 006c8583836..1da34227ee8 100644 --- a/dbms/src/Parsers/ASTRenameQuery.h +++ b/dbms/src/Parsers/ASTRenameQuery.h @@ -41,10 +41,10 @@ public: ASTPtr getRewrittenASTWithoutOnCluster(const std::string & new_database) const override { auto query_ptr = clone(); - auto & query = static_cast(*query_ptr); + auto * query = query_ptr->As(); - query.cluster.clear(); - for (Element & elem : query.elements) + query->cluster.clear(); + for (Element & elem : query->elements) { if (elem.from.database.empty()) elem.from.database = new_database; diff --git a/dbms/src/Parsers/ASTSelectQuery.cpp b/dbms/src/Parsers/ASTSelectQuery.cpp index f1cd92541c1..dced5f4159a 100644 --- a/dbms/src/Parsers/ASTSelectQuery.cpp +++ b/dbms/src/Parsers/ASTSelectQuery.cpp @@ -161,15 +161,15 @@ static const ASTTableExpression * getFirstTableExpression(const ASTSelectQuery & if (!select.tables) return {}; - const ASTTablesInSelectQuery & tables_in_select_query = static_cast(*select.tables); - if (tables_in_select_query.children.empty()) + const auto * tables_in_select_query = select.tables->As(); + if (tables_in_select_query->children.empty()) return {}; - const ASTTablesInSelectQueryElement & tables_element = static_cast(*tables_in_select_query.children[0]); - if (!tables_element.table_expression) + const auto * tables_element = tables_in_select_query->children[0]->As(); + if (!tables_element->table_expression) return {}; - return static_cast(tables_element.table_expression.get()); + return tables_element->table_expression->As(); } static ASTTableExpression * getFirstTableExpression(ASTSelectQuery & select) @@ -177,15 +177,15 @@ static ASTTableExpression * getFirstTableExpression(ASTSelectQuery & select) if (!select.tables) return {}; - ASTTablesInSelectQuery & tables_in_select_query = static_cast(*select.tables); - if (tables_in_select_query.children.empty()) + auto * tables_in_select_query = select.tables->As(); + if (tables_in_select_query->children.empty()) return {}; - ASTTablesInSelectQueryElement & tables_element = static_cast(*tables_in_select_query.children[0]); - if (!tables_element.table_expression) + auto * tables_element = tables_in_select_query->children[0]->As(); + if (!tables_element->table_expression) return {}; - return static_cast(tables_element.table_expression.get()); + return tables_element->table_expression->As(); } static const ASTArrayJoin * getFirstArrayJoin(const ASTSelectQuery & select) @@ -193,18 +193,18 @@ static const ASTArrayJoin * getFirstArrayJoin(const ASTSelectQuery & select) if (!select.tables) return {}; - const ASTTablesInSelectQuery & tables_in_select_query = static_cast(*select.tables); - if (tables_in_select_query.children.empty()) + const auto * tables_in_select_query = select.tables->As(); + if (tables_in_select_query->children.empty()) return {}; const ASTArrayJoin * array_join = nullptr; - for (const auto & child : tables_in_select_query.children) + for (const auto & child : tables_in_select_query->children) { - const ASTTablesInSelectQueryElement & tables_element = static_cast(*child); - if (tables_element.array_join) + const auto * tables_element = child->As(); + if (tables_element->array_join) { if (!array_join) - array_join = static_cast(tables_element.array_join.get()); + array_join = tables_element->array_join->As(); else throw Exception("Support for more than one ARRAY JOIN in query is not implemented", ErrorCodes::NOT_IMPLEMENTED); } @@ -218,18 +218,18 @@ static const ASTTablesInSelectQueryElement * getFirstTableJoin(const ASTSelectQu if (!select.tables) return {}; - const ASTTablesInSelectQuery & tables_in_select_query = static_cast(*select.tables); - if (tables_in_select_query.children.empty()) + const auto * tables_in_select_query = select.tables->As(); + if (tables_in_select_query->children.empty()) return {}; const ASTTablesInSelectQueryElement * joined_table = nullptr; - for (const auto & child : tables_in_select_query.children) + for (const auto & child : tables_in_select_query->children) { - const ASTTablesInSelectQueryElement & tables_element = static_cast(*child); - if (tables_element.table_join) + const auto * tables_element = child->As(); + if (tables_element->table_join) { if (!joined_table) - joined_table = &tables_element; + joined_table = tables_element; else throw Exception("Multiple JOIN disabled or does not support the query. " "'set allow_experimental_multiple_joins_emulation' to enable.", ErrorCodes::NOT_IMPLEMENTED); diff --git a/dbms/src/Parsers/ASTTablesInSelectQuery.cpp b/dbms/src/Parsers/ASTTablesInSelectQuery.cpp index 2f3e645a99a..3947200f705 100644 --- a/dbms/src/Parsers/ASTTablesInSelectQuery.cpp +++ b/dbms/src/Parsers/ASTTablesInSelectQuery.cpp @@ -218,7 +218,7 @@ void ASTTablesInSelectQueryElement::formatImpl(const FormatSettings & settings, { if (table_join) { - static_cast(*table_join).formatImplBeforeTable(settings, state, frame); + table_join->As()->formatImplBeforeTable(settings, state, frame); settings.ostr << " "; } @@ -226,7 +226,7 @@ void ASTTablesInSelectQueryElement::formatImpl(const FormatSettings & settings, settings.ostr << " "; if (table_join) - static_cast(*table_join).formatImplAfterTable(settings, state, frame); + table_join->As()->formatImplAfterTable(settings, state, frame); } else if (array_join) { diff --git a/dbms/src/Parsers/ExpressionElementParsers.cpp b/dbms/src/Parsers/ExpressionElementParsers.cpp index 786db068af7..4a1c7393d99 100644 --- a/dbms/src/Parsers/ExpressionElementParsers.cpp +++ b/dbms/src/Parsers/ExpressionElementParsers.cpp @@ -82,18 +82,18 @@ bool ParserParenthesisExpression::parseImpl(Pos & pos, ASTPtr & node, Expected & return false; ++pos; - ASTExpressionList & expr_list = typeid_cast(*contents_node); + const auto * expr_list = contents_node->As(); /// empty expression in parentheses is not allowed - if (expr_list.children.empty()) + if (expr_list->children.empty()) { expected.add(pos, "non-empty parenthesized list of expressions"); return false; } - if (expr_list.children.size() == 1) + if (expr_list->children.size() == 1) { - node = expr_list.children.front(); + node = expr_list->children.front(); } else { @@ -125,7 +125,7 @@ bool ParserSubquery::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) ++pos; node = std::make_shared(); - typeid_cast(*node).children.push_back(select_node); + node->children.push_back(select_node); return true; } @@ -170,8 +170,8 @@ bool ParserCompoundIdentifier::parseImpl(Pos & pos, ASTPtr & node, Expected & ex String name; std::vector parts; - const ASTExpressionList & list = static_cast(*id_list.get()); - for (const auto & child : list.children) + const auto * list = id_list->As(); + for (const auto & child : list->children) { if (!name.empty()) name += '.'; @@ -1254,7 +1254,7 @@ bool ParserWithOptionalAlias::parseImpl(Pos & pos, ASTPtr & node, Expected & exp ASTPtr alias_node; if (ParserAlias(allow_alias_without_as_keyword_now).parse(pos, alias_node, expected)) { - if (ASTWithAlias * ast_with_alias = dynamic_cast(node.get())) + if (auto * ast_with_alias = node->As()) { getIdentifierName(alias_node, ast_with_alias->alias); ast_with_alias->prefer_alias_to_column_name = prefer_alias_to_column_name; diff --git a/dbms/src/Parsers/ExpressionListParsers.cpp b/dbms/src/Parsers/ExpressionListParsers.cpp index 00f72d6a369..ba59a01ddeb 100644 --- a/dbms/src/Parsers/ExpressionListParsers.cpp +++ b/dbms/src/Parsers/ExpressionListParsers.cpp @@ -213,7 +213,7 @@ bool ParserVariableArityOperatorList::parseImpl(Pos & pos, ASTPtr & node, Expect if (!arguments) { node = makeASTFunction(function_name, node); - arguments = static_cast(*node).arguments; + arguments = node->As()->arguments; } ASTPtr elem; @@ -540,8 +540,7 @@ bool ParserExpressionList::parseImpl(Pos & pos, ASTPtr & node, Expected & expect bool ParserNotEmptyExpressionList::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) { - return nested_parser.parse(pos, node, expected) - && !typeid_cast(*node).children.empty(); + return nested_parser.parse(pos, node, expected) && !node->children.empty(); } diff --git a/dbms/src/Parsers/ParserDropQuery.cpp b/dbms/src/Parsers/ParserDropQuery.cpp index c3a97a222d2..21b034dbbec 100644 --- a/dbms/src/Parsers/ParserDropQuery.cpp +++ b/dbms/src/Parsers/ParserDropQuery.cpp @@ -34,7 +34,7 @@ bool ParserDropQuery::parseDetachQuery(Pos & pos, ASTPtr & node, Expected & expe { if (parseDropQuery(pos, node, expected)) { - ASTDropQuery * drop_query = static_cast(node.get()); + auto * drop_query = node->As(); drop_query->kind = ASTDropQuery::Kind::Detach; return true; } @@ -45,7 +45,7 @@ bool ParserDropQuery::parseTruncateQuery(Pos & pos, ASTPtr & node, Expected & ex { if (parseDropQuery(pos, node, expected)) { - ASTDropQuery * drop_query = static_cast(node.get()); + auto * drop_query = node->As(); drop_query->kind = ASTDropQuery::Kind::Truncate; return true; } diff --git a/dbms/src/Parsers/ParserPartition.cpp b/dbms/src/Parsers/ParserPartition.cpp index 33dc47514b3..abb972a1aa7 100644 --- a/dbms/src/Parsers/ParserPartition.cpp +++ b/dbms/src/Parsers/ParserPartition.cpp @@ -26,7 +26,7 @@ bool ParserPartition::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) if (!parser_string_literal.parse(pos, partition_id, expected)) return false; - partition->id = dynamic_cast(*partition_id).value.get(); + partition->id = partition_id->As()->value.get(); } else { @@ -40,7 +40,7 @@ bool ParserPartition::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) const auto * tuple_ast = value->As(); if (tuple_ast && tuple_ast->name == "tuple") { - const auto * arguments_ast = dynamic_cast(tuple_ast->arguments.get()); + const auto * arguments_ast = tuple_ast->arguments->As(); if (arguments_ast) fields_count = arguments_ast->children.size(); else diff --git a/dbms/src/Parsers/ParserQueryWithOutput.cpp b/dbms/src/Parsers/ParserQueryWithOutput.cpp index d1679067854..35c78bb91e6 100644 --- a/dbms/src/Parsers/ParserQueryWithOutput.cpp +++ b/dbms/src/Parsers/ParserQueryWithOutput.cpp @@ -62,16 +62,16 @@ bool ParserQueryWithOutput::parseImpl(Pos & pos, ASTPtr & node, Expected & expec if (!parsed) return false; - auto & query_with_output = dynamic_cast(*query); + auto * query_with_output = query->As(); ParserKeyword s_into_outfile("INTO OUTFILE"); if (s_into_outfile.ignore(pos, expected)) { ParserStringLiteral out_file_p; - if (!out_file_p.parse(pos, query_with_output.out_file, expected)) + if (!out_file_p.parse(pos, query_with_output->out_file, expected)) return false; - query_with_output.children.push_back(query_with_output.out_file); + query_with_output->children.push_back(query_with_output->out_file); } ParserKeyword s_format("FORMAT"); @@ -80,11 +80,11 @@ bool ParserQueryWithOutput::parseImpl(Pos & pos, ASTPtr & node, Expected & expec { ParserIdentifier format_p; - if (!format_p.parse(pos, query_with_output.format, expected)) + if (!format_p.parse(pos, query_with_output->format, expected)) return false; - setIdentifierSpecial(query_with_output.format); + setIdentifierSpecial(query_with_output->format); - query_with_output.children.push_back(query_with_output.format); + query_with_output->children.push_back(query_with_output->format); } // SETTINGS key1 = value1, key2 = value2, ... @@ -92,9 +92,9 @@ bool ParserQueryWithOutput::parseImpl(Pos & pos, ASTPtr & node, Expected & expec if (s_settings.ignore(pos, expected)) { ParserSetQuery parser_settings(true); - if (!parser_settings.parse(pos, query_with_output.settings_ast, expected)) + if (!parser_settings.parse(pos, query_with_output->settings_ast, expected)) return false; - query_with_output.children.push_back(query_with_output.settings_ast); + query_with_output->children.push_back(query_with_output->settings_ast); } if (explain_ast) diff --git a/dbms/src/Parsers/ParserSelectWithUnionQuery.cpp b/dbms/src/Parsers/ParserSelectWithUnionQuery.cpp index a0935074771..ff2f13342ef 100644 --- a/dbms/src/Parsers/ParserSelectWithUnionQuery.cpp +++ b/dbms/src/Parsers/ParserSelectWithUnionQuery.cpp @@ -11,7 +11,7 @@ namespace DB static void getSelectsFromUnionListNode(ASTPtr & ast_select, ASTs & selects) { - if (ASTSelectWithUnionQuery * inner_union = typeid_cast(ast_select.get())) + if (auto * inner_union = ast_select->As()) { for (auto & child : inner_union->list_of_selects->children) getSelectsFromUnionListNode(child, selects); diff --git a/dbms/src/Parsers/ParserShowTablesQuery.cpp b/dbms/src/Parsers/ParserShowTablesQuery.cpp index dc854883cfe..4a95ca3b1ee 100644 --- a/dbms/src/Parsers/ParserShowTablesQuery.cpp +++ b/dbms/src/Parsers/ParserShowTablesQuery.cpp @@ -67,7 +67,7 @@ bool ParserShowTablesQuery::parseImpl(Pos & pos, ASTPtr & node, Expected & expec getIdentifierName(database, query->from); if (like) - query->like = safeGet(typeid_cast(*like).value); + query->like = safeGet(like->As()->value); node = query; diff --git a/dbms/src/Parsers/ParserUnionQueryElement.cpp b/dbms/src/Parsers/ParserUnionQueryElement.cpp index e6b8ba66cb0..1e1e1908384 100644 --- a/dbms/src/Parsers/ParserUnionQueryElement.cpp +++ b/dbms/src/Parsers/ParserUnionQueryElement.cpp @@ -13,7 +13,7 @@ bool ParserUnionQueryElement::parseImpl(Pos & pos, ASTPtr & node, Expected & exp if (!ParserSubquery().parse(pos, node, expected) && !ParserSelectQuery().parse(pos, node, expected)) return false; - if (auto * ast_subquery = typeid_cast(node.get())) + if (const auto * ast_subquery = node->As()) node = ast_subquery->children.at(0); return true; diff --git a/dbms/src/Parsers/parseQuery.cpp b/dbms/src/Parsers/parseQuery.cpp index 4f8ab83b7fd..5eb128ae6ec 100644 --- a/dbms/src/Parsers/parseQuery.cpp +++ b/dbms/src/Parsers/parseQuery.cpp @@ -236,7 +236,7 @@ ASTPtr tryParseQuery( /// If parsed query ends at data for insertion. Data for insertion could be in any format and not necessary be lexical correct. ASTInsertQuery * insert = nullptr; if (parse_res) - insert = typeid_cast(res.get()); + insert = res->As(); if (!(insert && insert->data)) { @@ -355,7 +355,7 @@ std::pair splitMultipartQuery(const std::string & queries, s ast = parseQueryAndMovePosition(parser, pos, end, "", true, 0); - ASTInsertQuery * insert = typeid_cast(ast.get()); + auto * insert = ast->As(); if (insert && insert->data) { diff --git a/dbms/src/Storages/AlterCommands.cpp b/dbms/src/Storages/AlterCommands.cpp index f432f3903dd..e36b97af712 100644 --- a/dbms/src/Storages/AlterCommands.cpp +++ b/dbms/src/Storages/AlterCommands.cpp @@ -109,8 +109,8 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = COMMENT_COLUMN; command.column_name = *getIdentifierName(command_ast->column); - const auto & ast_comment = typeid_cast(*command_ast->comment); - command.comment = ast_comment.value.get(); + const auto * ast_comment = command_ast->comment->As(); + command.comment = ast_comment->value.get(); command.if_exists = command_ast->if_exists; return command; } diff --git a/dbms/src/Storages/ColumnsDescription.cpp b/dbms/src/Storages/ColumnsDescription.cpp index 1d9313fe0db..d4baa0ed635 100644 --- a/dbms/src/Storages/ColumnsDescription.cpp +++ b/dbms/src/Storages/ColumnsDescription.cpp @@ -185,7 +185,7 @@ void parseColumn(ReadBufferFromString & buf, ColumnsDescription & result, const result.ordinary.emplace_back(column_name, std::move(type)); if (col_ast->comment) - if (auto comment_str = typeid_cast(*col_ast->comment).value.get(); !comment_str.empty()) + if (auto comment_str = col_ast->comment->As()->value.get(); !comment_str.empty()) result.comments.emplace(column_name, std::move(comment_str)); if (col_ast->codec) diff --git a/dbms/src/Storages/Kafka/StorageKafka.cpp b/dbms/src/Storages/Kafka/StorageKafka.cpp index 6b3f06e2c0c..80aae9ebe18 100644 --- a/dbms/src/Storages/Kafka/StorageKafka.cpp +++ b/dbms/src/Storages/Kafka/StorageKafka.cpp @@ -429,7 +429,7 @@ void registerStorageKafka(StorageFactory & factory) if (args_count >= 2) { engine_args[1] = evaluateConstantExpressionAsLiteral(engine_args[1], args.local_context); - topic_list = static_cast(*engine_args[1]).value.safeGet(); + topic_list = engine_args[1]->As()->value.safeGet(); } else if (kafka_settings.kafka_topic_list.changed) { @@ -447,7 +447,7 @@ void registerStorageKafka(StorageFactory & factory) if (args_count >= 3) { engine_args[2] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[2], args.local_context); - group = static_cast(*engine_args[2]).value.safeGet(); + group = engine_args[2]->As()->value.safeGet(); } else if (kafka_settings.kafka_group_name.changed) { diff --git a/dbms/src/Storages/MergeTree/KeyCondition.cpp b/dbms/src/Storages/MergeTree/KeyCondition.cpp index 4e631949f14..e75228d4cb0 100644 --- a/dbms/src/Storages/MergeTree/KeyCondition.cpp +++ b/dbms/src/Storages/MergeTree/KeyCondition.cpp @@ -370,11 +370,11 @@ void KeyCondition::traverseAST(const ASTPtr & node, const Context & context, Blo { RPNElement element; - if (ASTFunction * func = typeid_cast(&*node)) + if (auto * func = node->As()) { if (operatorFromAST(func, element)) { - auto & args = typeid_cast(*func->arguments).children; + auto & args = func->arguments->children; for (size_t i = 0, size = args.size(); i < size; ++i) { traverseAST(args[i], context, block_with_constants); diff --git a/dbms/src/Storages/MergeTree/MergeTreeData.cpp b/dbms/src/Storages/MergeTree/MergeTreeData.cpp index 2bfbf03f3de..293b41ead0a 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeData.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeData.cpp @@ -1174,14 +1174,14 @@ void MergeTreeData::createConvertExpression(const DataPartPtr & part, const Name /// Remove old indices std::set new_indices_set; for (const auto & index_decl : new_indices) - new_indices_set.emplace(dynamic_cast(*index_decl.get()).name); + new_indices_set.emplace(index_decl->As()->name); for (const auto & index_decl : old_indices) { - const auto & index = dynamic_cast(*index_decl.get()); - if (!new_indices_set.count(index.name)) + const auto * index = index_decl->As(); + if (!new_indices_set.count(index->name)) { - out_rename_map["skp_idx_" + index.name + ".idx"] = ""; - out_rename_map["skp_idx_" + index.name + ".mrk"] = ""; + out_rename_map["skp_idx_" + index->name + ".idx"] = ""; + out_rename_map["skp_idx_" + index->name + ".mrk"] = ""; } } @@ -2219,9 +2219,8 @@ void MergeTreeData::freezePartition(const ASTPtr & partition_ast, const String & if (format_version < MERGE_TREE_DATA_MIN_FORMAT_VERSION_WITH_CUSTOM_PARTITIONING) { - const auto & partition = dynamic_cast(*partition_ast); /// Month-partitioning specific - partition value can represent a prefix of the partition to freeze. - if (const auto * partition_lit = dynamic_cast(partition.value.get())) + if (const auto * partition_lit = partition_ast->As()->value->As()) prefix = partition_lit->value.getType() == Field::Types::UInt64 ? toString(partition_lit->value.get()) : partition_lit->value.safeGet(); diff --git a/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp b/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp index facce694ac6..339f817eedf 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp @@ -287,10 +287,10 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( RelativeSize relative_sample_size = 0; RelativeSize relative_sample_offset = 0; - ASTSelectQuery & select = typeid_cast(*query_info.query); + const auto * select = query_info.query->As(); - auto select_sample_size = select.sample_size(); - auto select_sample_offset = select.sample_offset(); + auto select_sample_size = select->sample_size(); + auto select_sample_offset = select->sample_offset(); if (select_sample_size) { @@ -515,8 +515,8 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( /// PREWHERE String prewhere_column; - if (select.prewhere_expression) - prewhere_column = select.prewhere_expression->getColumnName(); + if (select->prewhere_expression) + prewhere_column = select->prewhere_expression->getColumnName(); RangesInDataParts parts_with_ranges; @@ -566,7 +566,7 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( BlockInputStreams res; - if (select.final()) + if (select->final()) { /// Add columns needed to calculate the sorting expression and the sign. std::vector add_columns = data.sorting_key_expr->getRequiredColumns(); diff --git a/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp b/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp index 01ef675ecac..a0e5ea59419 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp @@ -223,8 +223,7 @@ void SetIndexCondition::traverseAST(ASTPtr & node) const { if (operatorFromAST(node)) { - auto * func = typeid_cast(&*node); - auto & args = typeid_cast(*func->arguments).children; + auto & args = node->As()->arguments->children; for (auto & arg : args) traverseAST(arg); @@ -245,7 +244,7 @@ bool SetIndexCondition::atomFromAST(ASTPtr & node) const if (const auto * identifier = node->As()) return key_columns.count(identifier->getColumnName()) != 0; - if (auto * func = typeid_cast(node.get())) + if (auto * func = node->As()) { if (key_columns.count(func->getColumnName())) { @@ -254,7 +253,7 @@ bool SetIndexCondition::atomFromAST(ASTPtr & node) const return true; } - ASTs & args = typeid_cast(*func->arguments).children; + auto & args = func->arguments->children; for (auto & arg : args) if (!atomFromAST(arg)) @@ -269,11 +268,11 @@ bool SetIndexCondition::atomFromAST(ASTPtr & node) const bool SetIndexCondition::operatorFromAST(ASTPtr & node) const { /// Functions AND, OR, NOT. Replace with bit*. - auto * func = typeid_cast(&*node); + auto * func = node->As(); if (!func) return false; - ASTs & args = typeid_cast(*func->arguments).children; + auto & args = func->arguments->children; if (func->name == "not") { diff --git a/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp b/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp index 64fc200d3b5..3bd77b33af4 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp @@ -44,9 +44,8 @@ MergeTreeWhereOptimizer::MergeTreeWhereOptimizer( first_primary_key_column = data.primary_key_columns[0]; calculateColumnSizes(data, queried_columns); - auto & select = typeid_cast(*query_info.query); - determineArrayJoinedNames(select); - optimize(select); + determineArrayJoinedNames(*query_info.query->As()); + optimize(*query_info.query->As()); } @@ -75,7 +74,7 @@ static void collectIdentifiersNoSubqueries(const ASTPtr & ast, NameSet & set) void MergeTreeWhereOptimizer::analyzeImpl(Conditions & res, const ASTPtr & node) const { - if (const auto func_and = typeid_cast(node.get()); func_and && func_and->name == "and") + if (const auto * func_and = node->As(); func_and && func_and->name == "and") { for (const auto & elem : func_and->arguments->children) analyzeImpl(res, elem); @@ -232,10 +231,10 @@ bool MergeTreeWhereOptimizer::isConditionGood(const ASTPtr & condition) const auto right_arg = function->arguments->children.back().get(); /// try to ensure left_arg points to ASTIdentifier - if (!isIdentifier(left_arg) && isIdentifier(right_arg)) + if (!left_arg->As() && right_arg->As()) std::swap(left_arg, right_arg); - if (isIdentifier(left_arg)) + if (left_arg->As()) { /// condition may be "good" if only right_arg is a constant and its value is outside the threshold if (const auto * literal = right_arg->As()) diff --git a/dbms/src/Storages/StorageBuffer.cpp b/dbms/src/Storages/StorageBuffer.cpp index b3cb485a6b4..0fbe7bdc829 100644 --- a/dbms/src/Storages/StorageBuffer.cpp +++ b/dbms/src/Storages/StorageBuffer.cpp @@ -713,17 +713,17 @@ void registerStorageBuffer(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); - String destination_database = static_cast(*engine_args[0]).value.safeGet(); - String destination_table = static_cast(*engine_args[1]).value.safeGet(); + String destination_database = engine_args[0]->As()->value.safeGet(); + String destination_table = engine_args[1]->As()->value.safeGet(); - UInt64 num_buckets = applyVisitor(FieldVisitorConvertToNumber(), typeid_cast(*engine_args[2]).value); + UInt64 num_buckets = applyVisitor(FieldVisitorConvertToNumber(), engine_args[2]->As()->value); - Int64 min_time = applyVisitor(FieldVisitorConvertToNumber(), typeid_cast(*engine_args[3]).value); - Int64 max_time = applyVisitor(FieldVisitorConvertToNumber(), typeid_cast(*engine_args[4]).value); - UInt64 min_rows = applyVisitor(FieldVisitorConvertToNumber(), typeid_cast(*engine_args[5]).value); - UInt64 max_rows = applyVisitor(FieldVisitorConvertToNumber(), typeid_cast(*engine_args[6]).value); - UInt64 min_bytes = applyVisitor(FieldVisitorConvertToNumber(), typeid_cast(*engine_args[7]).value); - UInt64 max_bytes = applyVisitor(FieldVisitorConvertToNumber(), typeid_cast(*engine_args[8]).value); + Int64 min_time = applyVisitor(FieldVisitorConvertToNumber(), engine_args[3]->As()->value); + Int64 max_time = applyVisitor(FieldVisitorConvertToNumber(), engine_args[4]->As()->value); + UInt64 min_rows = applyVisitor(FieldVisitorConvertToNumber(), engine_args[5]->As()->value); + UInt64 max_rows = applyVisitor(FieldVisitorConvertToNumber(), engine_args[6]->As()->value); + UInt64 min_bytes = applyVisitor(FieldVisitorConvertToNumber(), engine_args[7]->As()->value); + UInt64 max_bytes = applyVisitor(FieldVisitorConvertToNumber(), engine_args[8]->As()->value); return StorageBuffer::create( args.table_name, args.columns, diff --git a/dbms/src/Storages/StorageDistributed.cpp b/dbms/src/Storages/StorageDistributed.cpp index 644576272d0..ab394517b96 100644 --- a/dbms/src/Storages/StorageDistributed.cpp +++ b/dbms/src/Storages/StorageDistributed.cpp @@ -75,9 +75,9 @@ ASTPtr rewriteSelectQuery(const ASTPtr & query, const std::string & database, co { auto modified_query_ast = query->clone(); if (table_function_ptr) - typeid_cast(*modified_query_ast).addTableFunction(table_function_ptr); + modified_query_ast->As()->addTableFunction(table_function_ptr); else - typeid_cast(*modified_query_ast).replaceDatabaseAndTable(database, table); + modified_query_ast->As()->replaceDatabaseAndTable(database, table); return modified_query_ast; } @@ -466,14 +466,14 @@ void StorageDistributed::ClusterNodeData::shutdownAndDropAllData() /// using constraints from "WHERE" condition, otherwise returns `nullptr` ClusterPtr StorageDistributed::skipUnusedShards(ClusterPtr cluster, const SelectQueryInfo & query_info) { - const auto & select = typeid_cast(*query_info.query); + const auto * select = query_info.query->As(); - if (!select.where_expression) + if (!select->where_expression) { return nullptr; } - const auto & blocks = evaluateExpressionOverConstantCondition(select.where_expression, sharding_key_expr); + const auto & blocks = evaluateExpressionOverConstantCondition(select->where_expression, sharding_key_expr); // Can't get definite answer if we can skip any shards if (!blocks) @@ -526,8 +526,8 @@ void registerStorageDistributed(StorageFactory & factory) engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); engine_args[2] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[2], args.local_context); - String remote_database = static_cast(*engine_args[1]).value.safeGet(); - String remote_table = static_cast(*engine_args[2]).value.safeGet(); + String remote_database = engine_args[1]->As()->value.safeGet(); + String remote_table = engine_args[2]->As()->value.safeGet(); const auto & sharding_key = engine_args.size() == 4 ? engine_args[3] : nullptr; diff --git a/dbms/src/Storages/StorageFile.cpp b/dbms/src/Storages/StorageFile.cpp index 563419dad30..12279cfcd5a 100644 --- a/dbms/src/Storages/StorageFile.cpp +++ b/dbms/src/Storages/StorageFile.cpp @@ -291,7 +291,7 @@ void registerStorageFile(StorageFactory & factory) ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); - String format_name = static_cast(*engine_args[0]).value.safeGet(); + String format_name = engine_args[0]->As()->value.safeGet(); int source_fd = -1; String source_path; diff --git a/dbms/src/Storages/StorageHDFS.cpp b/dbms/src/Storages/StorageHDFS.cpp index 4f6cf35c09e..7bc6ee54062 100644 --- a/dbms/src/Storages/StorageHDFS.cpp +++ b/dbms/src/Storages/StorageHDFS.cpp @@ -163,11 +163,11 @@ void registerStorageHDFS(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); - String url = static_cast(*engine_args[0]).value.safeGet(); + String url = engine_args[0]->As()->value.safeGet(); engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); - String format_name = static_cast(*engine_args[1]).value.safeGet(); + String format_name = engine_args[0]->As()->value.safeGet(); return StorageHDFS::create(url, args.table_name, format_name, args.columns, args.context); }); diff --git a/dbms/src/Storages/StorageMaterializedView.cpp b/dbms/src/Storages/StorageMaterializedView.cpp index d27991114e7..223a23da35a 100644 --- a/dbms/src/Storages/StorageMaterializedView.cpp +++ b/dbms/src/Storages/StorageMaterializedView.cpp @@ -48,14 +48,14 @@ static void extractDependentTable(ASTSelectQuery & query, String & select_databa else select_database_name = db_and_table->database; } - else if (auto ast_select = typeid_cast(subquery.get())) + else if (auto * ast_select = subquery->As()) { if (ast_select->list_of_selects->children.size() != 1) throw Exception("UNION is not supported for MATERIALIZED VIEW", ErrorCodes::QUERY_IS_NOT_SUPPORTED_IN_MATERIALIZED_VIEW); auto & inner_query = ast_select->list_of_selects->children.at(0); - extractDependentTable(typeid_cast(*inner_query), select_database_name, select_table_name); + extractDependentTable(*inner_query->As(), select_database_name, select_table_name); } else throw Exception("Logical error while creating StorageMaterializedView." @@ -110,9 +110,9 @@ StorageMaterializedView::StorageMaterializedView( inner_query = query.select->list_of_selects->children.at(0); - ASTSelectQuery & select_query = typeid_cast(*inner_query); - extractDependentTable(select_query, select_database_name, select_table_name); - checkAllowedQueries(select_query); + auto * select_query = inner_query->As(); + extractDependentTable(*select_query, select_database_name, select_table_name); + checkAllowedQueries(*select_query); if (!select_table_name.empty()) global_context.addDependency( diff --git a/dbms/src/Storages/StorageMerge.cpp b/dbms/src/Storages/StorageMerge.cpp index d8e3dfce649..25e7e099ba6 100644 --- a/dbms/src/Storages/StorageMerge.cpp +++ b/dbms/src/Storages/StorageMerge.cpp @@ -289,7 +289,7 @@ BlockInputStreams StorageMerge::createSourceStreams(const SelectQueryInfo & quer } else if (processed_stage > storage->getQueryProcessingStage(modified_context)) { - typeid_cast(modified_query_info.query.get())->replaceDatabaseAndTable(source_database, storage->getTableName()); + modified_query_info.query->As()->replaceDatabaseAndTable(source_database, storage->getTableName()); /// Maximum permissible parallelism is streams_num modified_context.getSettingsRef().max_threads = UInt64(streams_num); @@ -369,7 +369,7 @@ StorageMerge::StorageListWithLocks StorageMerge::getSelectedTables(const ASTPtr { StoragePtr storage = iterator->table(); - if (query && typeid_cast(query.get())->prewhere_expression && !storage->supportsPrewhere()) + if (query && query->As()->prewhere_expression && !storage->supportsPrewhere()) throw Exception("Storage " + storage->getName() + " doesn't support PREWHERE.", ErrorCodes::ILLEGAL_PREWHERE); if (storage.get() != this) @@ -438,7 +438,7 @@ void StorageMerge::convertingSourceStream(const Block & header, const Context & Block before_block_header = source_stream->getHeader(); source_stream = std::make_shared(context, source_stream, header, ConvertingBlockInputStream::MatchColumnsMode::Name); - ASTPtr where_expression = typeid_cast(query.get())->where_expression; + auto where_expression = query->As()->where_expression; if (!where_expression) return; @@ -489,8 +489,8 @@ void registerStorageMerge(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); engine_args[1] = evaluateConstantExpressionAsLiteral(engine_args[1], args.local_context); - String source_database = static_cast(*engine_args[0]).value.safeGet(); - String table_name_regexp = static_cast(*engine_args[1]).value.safeGet(); + String source_database = engine_args[0]->As()->value.safeGet(); + String table_name_regexp = engine_args[1]->As()->value.safeGet(); return StorageMerge::create( args.table_name, args.columns, diff --git a/dbms/src/Storages/StorageMergeTree.cpp b/dbms/src/Storages/StorageMergeTree.cpp index 6f5fa7ef5ee..6f03e9eb885 100644 --- a/dbms/src/Storages/StorageMergeTree.cpp +++ b/dbms/src/Storages/StorageMergeTree.cpp @@ -234,13 +234,13 @@ void StorageMergeTree::alter( IDatabase::ASTModifier storage_modifier = [&] (IAST & ast) { - auto & storage_ast = typeid_cast(ast); + auto * storage_ast = ast.As(); if (new_order_by_ast.get() != data.order_by_ast.get()) - storage_ast.set(storage_ast.order_by, new_order_by_ast); + storage_ast->set(storage_ast->order_by, new_order_by_ast); if (new_primary_key_ast.get() != data.primary_key_ast.get()) - storage_ast.set(storage_ast.primary_key, new_primary_key_ast); + storage_ast->set(storage_ast->primary_key, new_primary_key_ast); }; context.getDatabase(current_database_name)->alterTable(context, current_table_name, new_columns, new_indices, storage_modifier); diff --git a/dbms/src/Storages/StorageMySQL.cpp b/dbms/src/Storages/StorageMySQL.cpp index 127caefcd3b..3bb1799ef50 100644 --- a/dbms/src/Storages/StorageMySQL.cpp +++ b/dbms/src/Storages/StorageMySQL.cpp @@ -199,21 +199,21 @@ void registerStorageMySQL(StorageFactory & factory) engine_args[i] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[i], args.local_context); /// 3306 is the default MySQL port. - auto parsed_host_port = parseAddress(static_cast(*engine_args[0]).value.safeGet(), 3306); + auto parsed_host_port = parseAddress(engine_args[0]->As()->value.safeGet(), 3306); - const String & remote_database = static_cast(*engine_args[1]).value.safeGet(); - const String & remote_table = static_cast(*engine_args[2]).value.safeGet(); - const String & username = static_cast(*engine_args[3]).value.safeGet(); - const String & password = static_cast(*engine_args[4]).value.safeGet(); + const String & remote_database = engine_args[1]->As()->value.safeGet(); + const String & remote_table = engine_args[2]->As()->value.safeGet(); + const String & username = engine_args[3]->As()->value.safeGet(); + const String & password = engine_args[4]->As()->value.safeGet(); mysqlxx::Pool pool(remote_database, parsed_host_port.first, username, password, parsed_host_port.second); bool replace_query = false; std::string on_duplicate_clause; if (engine_args.size() >= 6) - replace_query = static_cast(*engine_args[5]).value.safeGet() > 0; + replace_query = engine_args[5]->As()->value.safeGet(); if (engine_args.size() == 7) - on_duplicate_clause = static_cast(*engine_args[6]).value.safeGet(); + on_duplicate_clause = engine_args[6]->As()->value.safeGet(); if (replace_query && !on_duplicate_clause.empty()) throw Exception( diff --git a/dbms/src/Storages/StorageReplicatedMergeTree.cpp b/dbms/src/Storages/StorageReplicatedMergeTree.cpp index 7c7a2d53c4d..30d132dc5a5 100644 --- a/dbms/src/Storages/StorageReplicatedMergeTree.cpp +++ b/dbms/src/Storages/StorageReplicatedMergeTree.cpp @@ -447,17 +447,17 @@ void StorageReplicatedMergeTree::setTableStructure(ColumnsDescription new_column storage_modifier = [&](IAST & ast) { - auto & storage_ast = typeid_cast(ast); + auto * storage_ast = ast.As(); - if (!storage_ast.order_by) + if (!storage_ast->order_by) throw Exception( "ALTER MODIFY ORDER BY of default-partitioned tables is not supported", ErrorCodes::LOGICAL_ERROR); if (new_primary_key_ast.get() != data.primary_key_ast.get()) - storage_ast.set(storage_ast.primary_key, new_primary_key_ast); + storage_ast->set(storage_ast->primary_key, new_primary_key_ast); - storage_ast.set(storage_ast.order_by, new_order_by_ast); + storage_ast->set(storage_ast->order_by, new_order_by_ast); }; } @@ -3974,17 +3974,17 @@ void StorageReplicatedMergeTree::sendRequestToLeaderReplica(const ASTPtr & query /// TODO: add setters and getters interface for database and table fields of AST auto new_query = query->clone(); - if (auto * alter = typeid_cast(new_query.get())) + if (auto * alter = new_query->As()) { alter->database = leader_address.database; alter->table = leader_address.table; } - else if (auto * optimize = typeid_cast(new_query.get())) + else if (auto * optimize = new_query->As()) { optimize->database = leader_address.database; optimize->table = leader_address.table; } - else if (auto * drop = typeid_cast(new_query.get()); drop->kind == ASTDropQuery::Kind::Truncate) + else if (auto * drop = new_query->As(); drop->kind == ASTDropQuery::Kind::Truncate) { drop->database = leader_address.database; drop->table = leader_address.table; diff --git a/dbms/src/Storages/StorageURL.cpp b/dbms/src/Storages/StorageURL.cpp index 3224527123b..7a60f22926f 100644 --- a/dbms/src/Storages/StorageURL.cpp +++ b/dbms/src/Storages/StorageURL.cpp @@ -202,12 +202,12 @@ void registerStorageURL(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); - String url = static_cast(*engine_args[0]).value.safeGet(); + String url = engine_args[0]->As()->value.safeGet(); Poco::URI uri(url); engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); - String format_name = static_cast(*engine_args[1]).value.safeGet(); + String format_name = engine_args[1]->As()->value.safeGet(); return StorageURL::create(uri, args.table_name, format_name, args.columns, args.context); }); diff --git a/dbms/src/Storages/StorageView.cpp b/dbms/src/Storages/StorageView.cpp index 97c085d16e3..ac0a3efadbe 100644 --- a/dbms/src/Storages/StorageView.cpp +++ b/dbms/src/Storages/StorageView.cpp @@ -54,7 +54,7 @@ BlockInputStreams StorageView::read( { auto new_inner_query = inner_query->clone(); auto new_outer_query = query_info.query->clone(); - auto new_outer_select = typeid_cast(new_outer_query.get()); + auto * new_outer_select = new_outer_query->As(); replaceTableNameWithSubquery(new_outer_select, new_inner_query); @@ -74,12 +74,12 @@ BlockInputStreams StorageView::read( void StorageView::replaceTableNameWithSubquery(ASTSelectQuery * select_query, ASTPtr & subquery) { - ASTTablesInSelectQueryElement * select_element = static_cast(select_query->tables->children[0].get()); + auto * select_element = select_query->tables->children[0]->As(); if (!select_element->table_expression) throw Exception("Logical error: incorrect table expression", ErrorCodes::LOGICAL_ERROR); - ASTTableExpression * table_expression = static_cast(select_element->table_expression.get()); + auto * table_expression = select_element->table_expression->As(); if (!table_expression->database_and_table_name) throw Exception("Logical error: incorrect table expression", ErrorCodes::LOGICAL_ERROR); diff --git a/dbms/src/Storages/StorageXDBC.cpp b/dbms/src/Storages/StorageXDBC.cpp index ac8f156305a..c1c49773eed 100644 --- a/dbms/src/Storages/StorageXDBC.cpp +++ b/dbms/src/Storages/StorageXDBC.cpp @@ -115,10 +115,10 @@ namespace BridgeHelperPtr bridge_helper = std::make_shared>(args.context, args.context.getSettingsRef().http_receive_timeout.value, - static_cast(*engine_args[0]).value.safeGet()); + engine_args[0]->As()->value.safeGet()); return std::make_shared(args.table_name, - static_cast(*engine_args[1]).value.safeGet(), - static_cast(*engine_args[2]).value.safeGet(), + engine_args[1]->As()->value.safeGet(), + engine_args[2]->As()->value.safeGet(), args.columns, args.context, bridge_helper); diff --git a/dbms/src/Storages/VirtualColumnUtils.cpp b/dbms/src/Storages/VirtualColumnUtils.cpp index 4f3fad45d7f..6da2bdc921b 100644 --- a/dbms/src/Storages/VirtualColumnUtils.cpp +++ b/dbms/src/Storages/VirtualColumnUtils.cpp @@ -76,18 +76,18 @@ String chooseSuffixForSet(const NamesAndTypesList & columns, const std::vector(*ast); - if (!select.with_expression_list) + auto * select = ast->As(); + if (!select->with_expression_list) { - select.with_expression_list = std::make_shared(); - select.children.insert(select.children.begin(), select.with_expression_list); + select->with_expression_list = std::make_shared(); + select->children.insert(select->children.begin(), select->with_expression_list); } - ASTExpressionList & with = typeid_cast(*select.with_expression_list); + auto * with = select->with_expression_list->As(); auto literal = std::make_shared(value); literal->alias = column_name; literal->prefer_alias_to_column_name = true; - with.children.push_back(literal); + with->children.push_back(literal); } /// Verifying that the function depends only on the specified columns @@ -126,11 +126,11 @@ static ASTPtr buildWhereExpression(const ASTs & functions) if (functions.size() == 1) return functions[0]; ASTPtr new_query = std::make_shared(); - ASTFunction & new_function = typeid_cast(*new_query); - new_function.name = "and"; - new_function.arguments = std::make_shared(); - new_function.arguments->children = functions; - new_function.children.push_back(new_function.arguments); + auto * new_function = new_query->As(); + new_function->name = "and"; + new_function->arguments = std::make_shared(); + new_function->arguments->children = functions; + new_function->children.push_back(new_function->arguments); return new_query; } diff --git a/dbms/src/Storages/getStructureOfRemoteTable.cpp b/dbms/src/Storages/getStructureOfRemoteTable.cpp index bf867c1cad8..c606a620c5f 100644 --- a/dbms/src/Storages/getStructureOfRemoteTable.cpp +++ b/dbms/src/Storages/getStructureOfRemoteTable.cpp @@ -39,7 +39,7 @@ ColumnsDescription getStructureOfRemoteTable( { if (shard_info.isLocal()) { - auto table_function = static_cast(table_func_ptr.get()); + const auto * table_function = table_func_ptr->As(); return TableFunctionFactory::instance().get(table_function->name, context)->execute(table_func_ptr, context)->getColumns(); } diff --git a/dbms/src/Storages/transformQueryForExternalDatabase.cpp b/dbms/src/Storages/transformQueryForExternalDatabase.cpp index 69da7143e87..b14420884b6 100644 --- a/dbms/src/Storages/transformQueryForExternalDatabase.cpp +++ b/dbms/src/Storages/transformQueryForExternalDatabase.cpp @@ -21,10 +21,10 @@ static void replaceConstFunction(IAST & node, const Context & context, const Nam for (size_t i = 0; i < node.children.size(); ++i) { auto child = node.children[i]; - if (ASTExpressionList * exp_list = typeid_cast(&*child)) + if (auto * exp_list = child->As()) replaceConstFunction(*exp_list, context, all_columns); - if (ASTFunction * function = typeid_cast(&*child)) + if (auto * function = child->As()) { NamesAndTypesList source_columns = all_columns; ASTPtr query = function->ptr(); @@ -76,7 +76,7 @@ static bool isCompatible(const IAST & node) return true; } - if (isIdentifier(&node)) + if (node.As()) return true; return false; @@ -112,7 +112,7 @@ String transformQueryForExternalDatabase( * copy only compatible parts of it. */ - ASTPtr & original_where = typeid_cast(*clone_query).where_expression; + auto & original_where = clone_query->As()->where_expression; if (original_where) { replaceConstFunction(*original_where, context, available_columns); diff --git a/dbms/src/TableFunctions/ITableFunctionFileLike.cpp b/dbms/src/TableFunctions/ITableFunctionFileLike.cpp index 6495fbb92e3..6f9e4ddd3d5 100644 --- a/dbms/src/TableFunctions/ITableFunctionFileLike.cpp +++ b/dbms/src/TableFunctions/ITableFunctionFileLike.cpp @@ -22,12 +22,12 @@ namespace ErrorCodes StoragePtr ITableFunctionFileLike::executeImpl(const ASTPtr & ast_function, const Context & context) const { // Parse args - ASTs & args_func = typeid_cast(*ast_function).children; + ASTs & args_func = ast_function->children; if (args_func.size() != 1) throw Exception("Table function '" + getName() + "' must have arguments.", ErrorCodes::LOGICAL_ERROR); - ASTs & args = typeid_cast(*args_func.at(0)).children; + ASTs & args = args_func.at(0)->children; if (args.size() != 3) throw Exception("Table function '" + getName() + "' requires exactly 3 arguments: filename, format and structure.", @@ -36,9 +36,9 @@ StoragePtr ITableFunctionFileLike::executeImpl(const ASTPtr & ast_function, cons for (size_t i = 0; i < 3; ++i) args[i] = evaluateConstantExpressionOrIdentifierAsLiteral(args[i], context); - std::string filename = static_cast(*args[0]).value.safeGet(); - std::string format = static_cast(*args[1]).value.safeGet(); - std::string structure = static_cast(*args[2]).value.safeGet(); + std::string filename = args[0]->As()->value.safeGet(); + std::string format = args[1]->As()->value.safeGet(); + std::string structure = args[2]->As()->value.safeGet(); // Create sample block std::vector structure_vals; diff --git a/dbms/src/TableFunctions/ITableFunctionXDBC.cpp b/dbms/src/TableFunctions/ITableFunctionXDBC.cpp index 14f03493846..df4686ab740 100644 --- a/dbms/src/TableFunctions/ITableFunctionXDBC.cpp +++ b/dbms/src/TableFunctions/ITableFunctionXDBC.cpp @@ -34,7 +34,7 @@ StoragePtr ITableFunctionXDBC::executeImpl(const ASTPtr & ast_function, const Co if (!args_func->arguments) throw Exception("Table function '" + getName() + "' must have arguments.", ErrorCodes::LOGICAL_ERROR); - ASTs & args = typeid_cast(*args_func->arguments).children; + ASTs & args = args_func->arguments->children; if (args.size() != 2 && args.size() != 3) throw Exception("Table function '" + getName() + "' requires 2 or 3 arguments: " + getName() + "('DSN', table) or " + getName() + "('DSN', schema, table)", @@ -49,14 +49,14 @@ StoragePtr ITableFunctionXDBC::executeImpl(const ASTPtr & ast_function, const Co if (args.size() == 3) { - connection_string = static_cast(*args[0]).value.safeGet(); - schema_name = static_cast(*args[1]).value.safeGet(); - table_name = static_cast(*args[2]).value.safeGet(); + connection_string = args[0]->As()->value.safeGet(); + schema_name = args[1]->As()->value.safeGet(); + table_name = args[2]->As()->value.safeGet(); } else if (args.size() == 2) { - connection_string = static_cast(*args[0]).value.safeGet(); - table_name = static_cast(*args[1]).value.safeGet(); + connection_string = args[0]->As()->value.safeGet(); + table_name = args[1]->As()->value.safeGet(); } /* Infer external table structure */ diff --git a/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp b/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp index 10a3ab2b4c6..94b4b0d4446 100644 --- a/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp +++ b/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp @@ -18,7 +18,7 @@ namespace ErrorCodes StoragePtr TableFunctionCatBoostPool::executeImpl(const ASTPtr & ast_function, const Context & context) const { - ASTs & args_func = typeid_cast(*ast_function).children; + ASTs & args_func = ast_function->children; std::string err = "Table function '" + getName() + "' requires 2 parameters: " + "column descriptions file, dataset description file"; @@ -26,7 +26,7 @@ StoragePtr TableFunctionCatBoostPool::executeImpl(const ASTPtr & ast_function, c if (args_func.size() != 1) throw Exception(err, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - ASTs & args = typeid_cast(*args_func.at(0)).children; + ASTs & args = args_func.at(0)->children; if (args.size() != 2) throw Exception(err, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); diff --git a/dbms/src/TableFunctions/TableFunctionMerge.cpp b/dbms/src/TableFunctions/TableFunctionMerge.cpp index b5dace28d41..9c7bfa37edc 100644 --- a/dbms/src/TableFunctions/TableFunctionMerge.cpp +++ b/dbms/src/TableFunctions/TableFunctionMerge.cpp @@ -56,14 +56,14 @@ static NamesAndTypesList chooseColumns(const String & source_database, const Str StoragePtr TableFunctionMerge::executeImpl(const ASTPtr & ast_function, const Context & context) const { - ASTs & args_func = typeid_cast(*ast_function).children; + ASTs & args_func = ast_function->children; if (args_func.size() != 1) throw Exception("Table function 'merge' requires exactly 2 arguments" " - name of source database and regexp for table names.", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - ASTs & args = typeid_cast(*args_func.at(0)).children; + ASTs & args = args_func.at(0)->children; if (args.size() != 2) throw Exception("Table function 'merge' requires exactly 2 arguments" @@ -73,8 +73,8 @@ StoragePtr TableFunctionMerge::executeImpl(const ASTPtr & ast_function, const Co args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(args[0], context); args[1] = evaluateConstantExpressionAsLiteral(args[1], context); - String source_database = static_cast(*args[0]).value.safeGet(); - String table_name_regexp = static_cast(*args[1]).value.safeGet(); + String source_database = args[0]->As()->value.safeGet(); + String table_name_regexp = args[1]->As()->value.safeGet(); auto res = StorageMerge::create( getName(), diff --git a/dbms/src/TableFunctions/TableFunctionMySQL.cpp b/dbms/src/TableFunctions/TableFunctionMySQL.cpp index 6b71a1b89cb..1d3ad537850 100644 --- a/dbms/src/TableFunctions/TableFunctionMySQL.cpp +++ b/dbms/src/TableFunctions/TableFunctionMySQL.cpp @@ -101,18 +101,18 @@ StoragePtr TableFunctionMySQL::executeImpl(const ASTPtr & ast_function, const Co for (size_t i = 0; i < args.size(); ++i) args[i] = evaluateConstantExpressionOrIdentifierAsLiteral(args[i], context); - std::string host_port = static_cast(*args[0]).value.safeGet(); - std::string database_name = static_cast(*args[1]).value.safeGet(); - std::string table_name = static_cast(*args[2]).value.safeGet(); - std::string user_name = static_cast(*args[3]).value.safeGet(); - std::string password = static_cast(*args[4]).value.safeGet(); + std::string host_port = args[0]->As()->value.safeGet(); + std::string database_name = args[1]->As()->value.safeGet(); + std::string table_name = args[2]->As()->value.safeGet(); + std::string user_name = args[3]->As()->value.safeGet(); + std::string password = args[4]->As()->value.safeGet(); bool replace_query = false; std::string on_duplicate_clause; if (args.size() >= 6) - replace_query = static_cast(*args[5]).value.safeGet() > 0; + replace_query = args[5]->As()->value.safeGet() > 0; if (args.size() == 7) - on_duplicate_clause = static_cast(*args[6]).value.safeGet(); + on_duplicate_clause = args[6]->As()->value.safeGet(); if (replace_query && !on_duplicate_clause.empty()) throw Exception( diff --git a/dbms/src/TableFunctions/TableFunctionNumbers.cpp b/dbms/src/TableFunctions/TableFunctionNumbers.cpp index 8226542d9ee..56a76b096ba 100644 --- a/dbms/src/TableFunctions/TableFunctionNumbers.cpp +++ b/dbms/src/TableFunctions/TableFunctionNumbers.cpp @@ -19,7 +19,7 @@ namespace ErrorCodes StoragePtr TableFunctionNumbers::executeImpl(const ASTPtr & ast_function, const Context & context) const { - if (const ASTFunction * function = typeid_cast(ast_function.get())) + if (const auto * function = ast_function->As()) { auto arguments = function->arguments->children; @@ -45,7 +45,7 @@ void registerTableFunctionNumbers(TableFunctionFactory & factory) UInt64 TableFunctionNumbers::evaluateArgument(const Context & context, ASTPtr & argument) const { - return static_cast(*evaluateConstantExpressionOrIdentifierAsLiteral(argument, context)).value.safeGet(); + return evaluateConstantExpressionOrIdentifierAsLiteral(argument, context)->As()->value.safeGet(); } } diff --git a/dbms/src/TableFunctions/TableFunctionRemote.cpp b/dbms/src/TableFunctions/TableFunctionRemote.cpp index 2b4a1240bec..c8a5febbf51 100644 --- a/dbms/src/TableFunctions/TableFunctionRemote.cpp +++ b/dbms/src/TableFunctions/TableFunctionRemote.cpp @@ -27,12 +27,12 @@ namespace ErrorCodes StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const Context & context) const { - ASTs & args_func = typeid_cast(*ast_function).children; + ASTs & args_func = ast_function->children; if (args_func.size() != 1) throw Exception(help_message, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - ASTs & args = typeid_cast(*args_func.at(0)).children; + ASTs & args = args_func.at(0)->children; const size_t max_args = is_cluster_function ? 3 : 5; if (args.size() < 2 || args.size() > max_args) @@ -63,7 +63,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C if (is_cluster_function) { ASTPtr ast_name = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context); - cluster_name = static_cast(*ast_name).value.safeGet(); + cluster_name = ast_name->As()->value.safeGet(); } else { @@ -83,7 +83,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C } else { - remote_database = static_cast(*args[arg_num]).value.safeGet(); + remote_database = args[arg_num]->As()->value.safeGet(); ++arg_num; @@ -103,7 +103,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C else { args[arg_num] = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context); - remote_table = static_cast(*args[arg_num]).value.safeGet(); + remote_table = args[arg_num]->As()->value.safeGet(); ++arg_num; } } From d1ead2207380c7c059a5e602c2ba4ece1ba0a2ce Mon Sep 17 00:00:00 2001 From: Ivan Lezhankin Date: Mon, 11 Mar 2019 16:22:51 +0300 Subject: [PATCH 03/11] =?UTF-8?q?Rename=20As<=E2=80=A6>=20=E2=86=92=20as?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dbms/programs/client/Client.cpp | 22 +++---- dbms/programs/copier/ClusterCopier.cpp | 22 +++---- .../parseAggregateFunctionParameters.cpp | 4 +- .../src/Compression/CompressionCodecDelta.cpp | 2 +- dbms/src/Compression/CompressionCodecLZ4.cpp | 2 +- dbms/src/Compression/CompressionCodecZSTD.cpp | 2 +- dbms/src/Compression/CompressionFactory.cpp | 6 +- .../InputStreamFromASTInsertQuery.cpp | 2 +- .../DataTypes/DataTypeAggregateFunction.cpp | 8 +-- dbms/src/DataTypes/DataTypeDateTime.cpp | 2 +- dbms/src/DataTypes/DataTypeEnum.cpp | 6 +- dbms/src/DataTypes/DataTypeFactory.cpp | 6 +- dbms/src/DataTypes/DataTypeFixedString.cpp | 2 +- dbms/src/DataTypes/DataTypeTuple.cpp | 2 +- dbms/src/DataTypes/DataTypesDecimal.cpp | 6 +- dbms/src/Databases/DatabaseOrdinary.cpp | 6 +- dbms/src/Databases/DatabasesCommon.cpp | 4 +- dbms/src/Interpreters/ActionsVisitor.cpp | 26 ++++---- dbms/src/Interpreters/AnalyzedJoin.cpp | 2 +- .../Interpreters/ArrayJoinedColumnsVisitor.h | 10 +-- .../ClusterProxy/SelectStreamFactory.cpp | 2 +- dbms/src/Interpreters/Context.cpp | 2 +- .../Interpreters/CrossToInnerJoinVisitor.cpp | 22 +++---- dbms/src/Interpreters/DDLWorker.cpp | 4 +- .../DatabaseAndTableWithAlias.cpp | 14 ++--- .../ExecuteScalarSubqueriesVisitor.cpp | 14 ++--- dbms/src/Interpreters/ExpressionAnalyzer.cpp | 62 +++++++++---------- dbms/src/Interpreters/ExternalTablesVisitor.h | 2 +- .../Interpreters/GlobalSubqueriesVisitor.h | 16 ++--- dbms/src/Interpreters/IdentifierSemantic.cpp | 6 +- .../InJoinSubqueriesPreprocessor.cpp | 22 +++---- .../Interpreters/InterpreterAlterQuery.cpp | 2 +- .../Interpreters/InterpreterCheckQuery.cpp | 2 +- .../Interpreters/InterpreterCreateQuery.cpp | 10 +-- .../Interpreters/InterpreterDescribeQuery.cpp | 8 +-- .../src/Interpreters/InterpreterDropQuery.cpp | 2 +- .../Interpreters/InterpreterExistsQuery.cpp | 2 +- .../Interpreters/InterpreterExplainQuery.cpp | 2 +- dbms/src/Interpreters/InterpreterFactory.cpp | 40 ++++++------ .../Interpreters/InterpreterInsertQuery.cpp | 6 +- .../InterpreterKillQueryQuery.cpp | 4 +- .../Interpreters/InterpreterOptimizeQuery.cpp | 2 +- .../Interpreters/InterpreterRenameQuery.cpp | 2 +- .../Interpreters/InterpreterSelectQuery.cpp | 50 +++++++-------- .../InterpreterSelectWithUnionQuery.cpp | 2 +- dbms/src/Interpreters/InterpreterSetQuery.cpp | 4 +- .../InterpreterShowCreateQuery.cpp | 2 +- .../InterpreterShowTablesQuery.cpp | 2 +- .../Interpreters/InterpreterSystemQuery.cpp | 4 +- dbms/src/Interpreters/InterpreterUseQuery.cpp | 2 +- .../JoinToSubqueryTransformVisitor.cpp | 26 ++++---- .../LogicalExpressionsOptimizer.cpp | 20 +++--- ...OptimizeIfWithConstantConditionVisitor.cpp | 12 ++-- .../PredicateExpressionsOptimizer.cpp | 22 +++---- dbms/src/Interpreters/ProcessList.cpp | 6 +- dbms/src/Interpreters/QueryAliasesVisitor.cpp | 6 +- dbms/src/Interpreters/QueryNormalizer.cpp | 18 +++--- .../RequiredSourceColumnsVisitor.cpp | 32 +++++----- dbms/src/Interpreters/Set.cpp | 8 +-- dbms/src/Interpreters/SyntaxAnalyzer.cpp | 42 ++++++------- .../TranslateQualifiedNamesVisitor.cpp | 30 ++++----- .../evaluateConstantExpression.cpp | 28 ++++----- dbms/src/Interpreters/executeQuery.cpp | 8 +-- dbms/src/Interpreters/getClusterName.cpp | 6 +- dbms/src/Interpreters/interpretSubquery.cpp | 10 +-- dbms/src/Interpreters/loadMetadata.cpp | 2 +- dbms/src/Parsers/ASTAlterQuery.h | 2 +- dbms/src/Parsers/ASTFunction.cpp | 8 +-- dbms/src/Parsers/ASTIdentifier.cpp | 6 +- dbms/src/Parsers/ASTQueryWithOutput.cpp | 2 +- dbms/src/Parsers/ASTRenameQuery.h | 2 +- dbms/src/Parsers/ASTSelectQuery.cpp | 32 +++++----- dbms/src/Parsers/ASTTablesInSelectQuery.cpp | 6 +- dbms/src/Parsers/ExpressionElementParsers.cpp | 8 +-- dbms/src/Parsers/ExpressionListParsers.cpp | 2 +- dbms/src/Parsers/IAST.h | 4 +- dbms/src/Parsers/IAST_fwd.h | 3 +- dbms/src/Parsers/ParserAlterQuery.cpp | 4 +- dbms/src/Parsers/ParserCreateQuery.cpp | 8 +-- dbms/src/Parsers/ParserDropQuery.cpp | 4 +- dbms/src/Parsers/ParserPartition.cpp | 6 +- dbms/src/Parsers/ParserQueryWithOutput.cpp | 2 +- .../Parsers/ParserSelectWithUnionQuery.cpp | 2 +- dbms/src/Parsers/ParserSetQuery.cpp | 2 +- dbms/src/Parsers/ParserShowTablesQuery.cpp | 2 +- dbms/src/Parsers/ParserUnionQueryElement.cpp | 2 +- .../parseIdentifierOrStringLiteral.cpp | 2 +- dbms/src/Parsers/parseQuery.cpp | 4 +- dbms/src/Storages/AlterCommands.cpp | 20 +++--- dbms/src/Storages/ColumnsDescription.cpp | 4 +- dbms/src/Storages/Kafka/StorageKafka.cpp | 18 +++--- dbms/src/Storages/MergeTree/KeyCondition.cpp | 16 ++--- dbms/src/Storages/MergeTree/MergeTreeData.cpp | 16 ++--- .../MergeTree/MergeTreeDataSelectExecutor.cpp | 12 ++-- .../MergeTree/MergeTreeSetSkippingIndex.cpp | 20 +++--- .../MergeTree/MergeTreeWhereOptimizer.cpp | 24 +++---- .../MergeTree/registerStorageMergeTree.cpp | 14 ++--- dbms/src/Storages/MutationCommands.cpp | 4 +- dbms/src/Storages/StorageBuffer.cpp | 18 +++--- dbms/src/Storages/StorageDictionary.cpp | 2 +- dbms/src/Storages/StorageDistributed.cpp | 10 +-- dbms/src/Storages/StorageFile.cpp | 4 +- dbms/src/Storages/StorageHDFS.cpp | 4 +- dbms/src/Storages/StorageMaterializedView.cpp | 10 +-- dbms/src/Storages/StorageMerge.cpp | 10 +-- dbms/src/Storages/StorageMergeTree.cpp | 4 +- dbms/src/Storages/StorageMySQL.cpp | 14 ++--- .../Storages/StorageReplicatedMergeTree.cpp | 10 +-- dbms/src/Storages/StorageURL.cpp | 4 +- dbms/src/Storages/StorageView.cpp | 6 +- dbms/src/Storages/StorageXDBC.cpp | 6 +- .../Storages/System/StorageSystemTables.cpp | 2 +- .../System/StorageSystemZooKeeper.cpp | 12 ++-- dbms/src/Storages/VirtualColumnUtils.cpp | 10 +-- .../Storages/getStructureOfRemoteTable.cpp | 2 +- .../transformQueryForExternalDatabase.cpp | 14 ++--- .../TableFunctions/ITableFunctionFileLike.cpp | 6 +- .../src/TableFunctions/ITableFunctionXDBC.cpp | 12 ++-- .../TableFunctionCatBoostPool.cpp | 2 +- .../src/TableFunctions/TableFunctionMerge.cpp | 4 +- .../src/TableFunctions/TableFunctionMySQL.cpp | 16 ++--- .../TableFunctions/TableFunctionNumbers.cpp | 4 +- .../TableFunctions/TableFunctionRemote.cpp | 10 +-- 123 files changed, 595 insertions(+), 594 deletions(-) diff --git a/dbms/programs/client/Client.cpp b/dbms/programs/client/Client.cpp index 8c0801bf9c8..8acb7ae6709 100644 --- a/dbms/programs/client/Client.cpp +++ b/dbms/programs/client/Client.cpp @@ -704,7 +704,7 @@ private: return true; } - auto * insert = ast->As(); + auto * insert = ast->as(); if (insert && insert->data) { @@ -802,7 +802,7 @@ private: connection->forceConnected(); /// INSERT query for which data transfer is needed (not an INSERT SELECT) is processed separately. - const auto * insert_query = parsed_query->As(); + const auto * insert_query = parsed_query->as(); if (insert_query && !insert_query->select) processInsertQuery(); else @@ -811,7 +811,7 @@ private: /// Do not change context (current DB, settings) in case of an exception. if (!got_exception) { - if (const auto * set_query = parsed_query->As()) + if (const auto * set_query = parsed_query->as()) { /// Save all changes in settings to avoid losing them if the connection is lost. for (const auto & change : set_query->changes) @@ -823,7 +823,7 @@ private: } } - if (const auto * use_query = parsed_query->As()) + if (const auto * use_query = parsed_query->as()) { const String & new_database = use_query->database; /// If the client initiates the reconnection, it takes the settings from the config. @@ -855,7 +855,7 @@ private: /// Convert external tables to ExternalTableData and send them using the connection. void sendExternalTables() { - const auto * select = parsed_query->As(); + const auto * select = parsed_query->as(); if (!select && !external_tables.empty()) throw Exception("External tables could be sent only with select query", ErrorCodes::BAD_ARGUMENTS); @@ -880,7 +880,7 @@ private: void processInsertQuery() { /// Send part of query without data, because data will be sent separately. - const auto * insert_query = parsed_query->As(); + const auto * insert_query = parsed_query->as(); String query_without_data = insert_query->data ? query.substr(0, insert_query->data - query.data()) : query; @@ -937,7 +937,7 @@ private: void sendData(Block & sample, const ColumnsDescription & columns_description) { /// If INSERT data must be sent. - const auto * insert_query = parsed_query->As(); + const auto * insert_query = parsed_query->as(); if (!insert_query) return; @@ -962,7 +962,7 @@ private: String current_format = insert_format; /// Data format can be specified in the INSERT query. - if (const auto * insert = parsed_query->As()) + if (const auto * insert = parsed_query->as()) { if (!insert->format.empty()) current_format = insert->format; @@ -1228,11 +1228,11 @@ private: String current_format = format; /// The query can specify output format or output file. - if (const auto * query_with_output = parsed_query->As()) + if (const auto * query_with_output = parsed_query->as()) { if (query_with_output->out_file) { - const auto * out_file_node = query_with_output->out_file->As(); + const auto * out_file_node = query_with_output->out_file->as(); const auto & out_file = out_file_node->value.safeGet(); out_file_buf.emplace(out_file, DBMS_DEFAULT_BUFFER_SIZE, O_WRONLY | O_EXCL | O_CREAT); @@ -1246,7 +1246,7 @@ private: { if (has_vertical_output_suffix) throw Exception("Output format already specified", ErrorCodes::CLIENT_OUTPUT_FORMAT_SPECIFIED); - const auto * id = query_with_output->format->As(); + const auto * id = query_with_output->format->as(); current_format = id->name; } if (query_with_output->settings_ast) diff --git a/dbms/programs/copier/ClusterCopier.cpp b/dbms/programs/copier/ClusterCopier.cpp index 67ddb1f13c9..79b13a03850 100644 --- a/dbms/programs/copier/ClusterCopier.cpp +++ b/dbms/programs/copier/ClusterCopier.cpp @@ -483,7 +483,7 @@ String DB::TaskShard::getHostNameExample() const static bool isExtendedDefinitionStorage(const ASTPtr & storage_ast) { - const auto * storage = storage_ast->As(); + const auto * storage = storage_ast->as(); return storage->partition_by || storage->order_by || storage->sample_by; } @@ -491,8 +491,8 @@ static ASTPtr extractPartitionKey(const ASTPtr & storage_ast) { String storage_str = queryToString(storage_ast); - const auto * storage = storage_ast->As(); - const auto * engine = storage->engine->As(); + const auto * storage = storage_ast->as(); + const auto * engine = storage->engine->as(); if (!endsWith(engine->name, "MergeTree")) { @@ -501,7 +501,7 @@ static ASTPtr extractPartitionKey(const ASTPtr & storage_ast) } ASTPtr arguments_ast = engine->arguments->clone(); - ASTs & arguments = arguments_ast->As()->children; // FIXME: what' the point of casting? + ASTs & arguments = arguments_ast->as()->children; // FIXME: what' the point of casting? if (isExtendedDefinitionStorage(storage_ast)) { @@ -1179,12 +1179,12 @@ protected: /// Removes MATERIALIZED and ALIAS columns from create table query static ASTPtr removeAliasColumnsFromCreateQuery(const ASTPtr & query_ast) { - const ASTs & column_asts = query_ast->As()->columns_list->columns->children; + const ASTs & column_asts = query_ast->as()->columns_list->columns->children; auto new_columns = std::make_shared(); for (const ASTPtr & column_ast : column_asts) { - const auto * column = column_ast->As(); + const auto * column = column_ast->as(); if (!column->default_specifier.empty()) { @@ -1197,11 +1197,11 @@ protected: } ASTPtr new_query_ast = query_ast->clone(); - auto * new_query = new_query_ast->As(); + auto * new_query = new_query_ast->as(); auto new_columns_list = std::make_shared(); new_columns_list->set(new_columns_list->columns, new_columns); - new_columns_list->set(new_columns_list->indices, query_ast->As()->columns_list->indices->clone()); + new_columns_list->set(new_columns_list->indices, query_ast->as()->columns_list->indices->clone()); new_query->replace(new_query->columns_list, new_columns_list); @@ -1211,7 +1211,7 @@ protected: /// Replaces ENGINE and table name in a create query std::shared_ptr rewriteCreateQueryStorage(const ASTPtr & create_query_ast, const DatabaseAndTableName & new_table, const ASTPtr & new_storage_ast) { - const auto * create = create_query_ast->As(); + const auto * create = create_query_ast->as(); auto res = std::make_shared(*create); if (create->storage == nullptr || new_storage_ast == nullptr) @@ -1645,7 +1645,7 @@ protected: /// Try create table (if not exists) on each shard { auto create_query_push_ast = rewriteCreateQueryStorage(task_shard.current_pull_table_create_query, task_table.table_push, task_table.engine_push_ast); - create_query_push_ast->As()->if_not_exists = true; + create_query_push_ast->as()->if_not_exists = true; String query = queryToString(create_query_push_ast); LOG_DEBUG(log, "Create destination tables. Query: " << query); @@ -1778,7 +1778,7 @@ protected: void dropAndCreateLocalTable(const ASTPtr & create_ast) { - const auto * create = create_ast->As(); + const auto * create = create_ast->as(); dropLocalTableIfExists({create->database, create->table}); InterpreterCreateQuery interpreter(create_ast, context); diff --git a/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp b/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp index bbfe2294fde..d724a297a7b 100644 --- a/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp +++ b/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp @@ -15,7 +15,7 @@ namespace ErrorCodes Array getAggregateFunctionParametersArray(const ASTPtr & expression_list, const std::string & error_context) { - const ASTs & parameters = expression_list->As()->children; + const ASTs & parameters = expression_list->as()->children; if (parameters.empty()) throw Exception("Parameters list to aggregate functions cannot be empty", ErrorCodes::BAD_ARGUMENTS); @@ -23,7 +23,7 @@ Array getAggregateFunctionParametersArray(const ASTPtr & expression_list, const for (size_t i = 0; i < parameters.size(); ++i) { - const auto * literal = parameters[i]->As(); + const auto * literal = parameters[i]->as(); if (!literal) { throw Exception("Parameters to aggregate functions must be literals" + (error_context.empty() ? "" : " (in " + error_context +")"), diff --git a/dbms/src/Compression/CompressionCodecDelta.cpp b/dbms/src/Compression/CompressionCodecDelta.cpp index 986875dd95f..08cc37864dd 100644 --- a/dbms/src/Compression/CompressionCodecDelta.cpp +++ b/dbms/src/Compression/CompressionCodecDelta.cpp @@ -144,7 +144,7 @@ void registerCodecDelta(CompressionCodecFactory & factory) throw Exception("Delta codec must have 1 parameter, given " + std::to_string(arguments->children.size()), ErrorCodes::ILLEGAL_SYNTAX_FOR_CODEC_TYPE); const auto children = arguments->children; - const auto * literal = children[0]->As(); + const auto * literal = children[0]->as(); size_t user_bytes_size = literal->value.safeGet(); if (user_bytes_size != 1 && user_bytes_size != 2 && user_bytes_size != 4 && user_bytes_size != 8) throw Exception("Delta value for delta codec can be 1, 2, 4 or 8, given " + toString(user_bytes_size), ErrorCodes::ILLEGAL_CODEC_PARAMETER); diff --git a/dbms/src/Compression/CompressionCodecLZ4.cpp b/dbms/src/Compression/CompressionCodecLZ4.cpp index 2340d85238f..08553e0920c 100644 --- a/dbms/src/Compression/CompressionCodecLZ4.cpp +++ b/dbms/src/Compression/CompressionCodecLZ4.cpp @@ -86,7 +86,7 @@ void registerCodecLZ4HC(CompressionCodecFactory & factory) throw Exception("LZ4HC codec must have 1 parameter, given " + std::to_string(arguments->children.size()), ErrorCodes::ILLEGAL_SYNTAX_FOR_CODEC_TYPE); const auto children = arguments->children; - const auto * literal = children[0]->As(); + const auto * literal = children[0]->as(); level = literal->value.safeGet(); } diff --git a/dbms/src/Compression/CompressionCodecZSTD.cpp b/dbms/src/Compression/CompressionCodecZSTD.cpp index 1e8eb99f4be..9e7e66a5e6e 100644 --- a/dbms/src/Compression/CompressionCodecZSTD.cpp +++ b/dbms/src/Compression/CompressionCodecZSTD.cpp @@ -73,7 +73,7 @@ void registerCodecZSTD(CompressionCodecFactory & factory) throw Exception("ZSTD codec must have 1 parameter, given " + std::to_string(arguments->children.size()), ErrorCodes::ILLEGAL_SYNTAX_FOR_CODEC_TYPE); const auto children = arguments->children; - const auto * literal = children[0]->As(); + const auto * literal = children[0]->as(); level = literal->value.safeGet(); if (level > ZSTD_maxCLevel()) throw Exception("ZSTD codec can't have level more that " + toString(ZSTD_maxCLevel()) + ", given " + toString(level), ErrorCodes::ILLEGAL_CODEC_PARAMETER); diff --git a/dbms/src/Compression/CompressionFactory.cpp b/dbms/src/Compression/CompressionFactory.cpp index 47d1a7ef1cc..ed34b8817d3 100644 --- a/dbms/src/Compression/CompressionFactory.cpp +++ b/dbms/src/Compression/CompressionFactory.cpp @@ -56,15 +56,15 @@ CompressionCodecPtr CompressionCodecFactory::get(const std::vectorAs()) + if (const auto * func = ast->as()) { Codecs codecs; codecs.reserve(func->arguments->children.size()); for (const auto & inner_codec_ast : func->arguments->children) { - if (const auto * family_name = inner_codec_ast->As()) + if (const auto * family_name = inner_codec_ast->as()) codecs.emplace_back(getImpl(family_name->name, {}, column_type)); - else if (const auto * ast_func = inner_codec_ast->As()) + else if (const auto * ast_func = inner_codec_ast->as()) codecs.emplace_back(getImpl(ast_func->name, ast_func->arguments, column_type)); else throw Exception("Unexpected AST element for compression codec", ErrorCodes::UNEXPECTED_AST_STRUCTURE); diff --git a/dbms/src/DataStreams/InputStreamFromASTInsertQuery.cpp b/dbms/src/DataStreams/InputStreamFromASTInsertQuery.cpp index 726148e8631..dc039648053 100644 --- a/dbms/src/DataStreams/InputStreamFromASTInsertQuery.cpp +++ b/dbms/src/DataStreams/InputStreamFromASTInsertQuery.cpp @@ -20,7 +20,7 @@ namespace ErrorCodes InputStreamFromASTInsertQuery::InputStreamFromASTInsertQuery( const ASTPtr & ast, ReadBuffer * input_buffer_tail_part, const Block & header, Context & context) { - const auto * ast_insert_query = ast->As(); + const auto * ast_insert_query = ast->as(); if (!ast_insert_query) throw Exception("Logical error: query requires data to insert, but it is not INSERT query", ErrorCodes::LOGICAL_ERROR); diff --git a/dbms/src/DataTypes/DataTypeAggregateFunction.cpp b/dbms/src/DataTypes/DataTypeAggregateFunction.cpp index c8c1c717659..c604d58cbaa 100644 --- a/dbms/src/DataTypes/DataTypeAggregateFunction.cpp +++ b/dbms/src/DataTypes/DataTypeAggregateFunction.cpp @@ -340,18 +340,18 @@ static DataTypePtr create(const ASTPtr & arguments) throw Exception("Data type AggregateFunction requires parameters: " "name of aggregate function and list of data types for arguments", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - if (const auto * parametric = arguments->children[0]->As()) + if (const auto * parametric = arguments->children[0]->as()) { if (parametric->parameters) throw Exception("Unexpected level of parameters to aggregate function", ErrorCodes::SYNTAX_ERROR); function_name = parametric->name; - const ASTs & parameters = parametric->arguments->As()->children; + const ASTs & parameters = parametric->arguments->as()->children; params_row.resize(parameters.size()); for (size_t i = 0; i < parameters.size(); ++i) { - const auto * literal = parameters[i]->As(); + const auto * literal = parameters[i]->as(); if (!literal) throw Exception("Parameters to aggregate functions must be literals", ErrorCodes::PARAMETERS_TO_AGGREGATE_FUNCTIONS_MUST_BE_LITERALS); @@ -363,7 +363,7 @@ static DataTypePtr create(const ASTPtr & arguments) { function_name = *opt_name; } - else if (arguments->children[0]->As()) + else if (arguments->children[0]->as()) { throw Exception("Aggregate function name for data type AggregateFunction must be passed as identifier (without quotes) or function", ErrorCodes::BAD_ARGUMENTS); diff --git a/dbms/src/DataTypes/DataTypeDateTime.cpp b/dbms/src/DataTypes/DataTypeDateTime.cpp index 08864cc9693..f3d6efa1488 100644 --- a/dbms/src/DataTypes/DataTypeDateTime.cpp +++ b/dbms/src/DataTypes/DataTypeDateTime.cpp @@ -186,7 +186,7 @@ static DataTypePtr create(const ASTPtr & arguments) if (arguments->children.size() != 1) throw Exception("DateTime data type can optionally have only one argument - time zone name", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - const auto * arg = arguments->children[0]->As(); + const auto * arg = arguments->children[0]->as(); if (!arg || arg->value.getType() != Field::Types::String) throw Exception("Parameter for DateTime data type must be string literal", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); diff --git a/dbms/src/DataTypes/DataTypeEnum.cpp b/dbms/src/DataTypes/DataTypeEnum.cpp index b59922ab1af..24f760a1800 100644 --- a/dbms/src/DataTypes/DataTypeEnum.cpp +++ b/dbms/src/DataTypes/DataTypeEnum.cpp @@ -357,7 +357,7 @@ static DataTypePtr create(const ASTPtr & arguments) /// Children must be functions 'equals' with string literal as left argument and numeric literal as right argument. for (const ASTPtr & child : arguments->children) { - const auto * func = child->As(); + const auto * func = child->as(); if (!func || func->name != "equals" || func->parameters @@ -366,8 +366,8 @@ static DataTypePtr create(const ASTPtr & arguments) throw Exception("Elements of Enum data type must be of form: 'name' = number, where name is string literal and number is an integer", ErrorCodes::UNEXPECTED_AST_STRUCTURE); - const auto * name_literal = func->arguments->children[0]->As(); - const auto * value_literal = func->arguments->children[1]->As(); + const auto * name_literal = func->arguments->children[0]->as(); + const auto * value_literal = func->arguments->children[1]->as(); if (!name_literal || !value_literal diff --git a/dbms/src/DataTypes/DataTypeFactory.cpp b/dbms/src/DataTypes/DataTypeFactory.cpp index 1c5aeeddf20..a0afab890e9 100644 --- a/dbms/src/DataTypes/DataTypeFactory.cpp +++ b/dbms/src/DataTypes/DataTypeFactory.cpp @@ -32,19 +32,19 @@ DataTypePtr DataTypeFactory::get(const String & full_name) const DataTypePtr DataTypeFactory::get(const ASTPtr & ast) const { - if (const auto * func = ast->As()) + if (const auto * func = ast->as()) { if (func->parameters) throw Exception("Data type cannot have multiple parenthesed parameters.", ErrorCodes::ILLEGAL_SYNTAX_FOR_DATA_TYPE); return get(func->name, func->arguments); } - if (const auto * ident = ast->As()) + if (const auto * ident = ast->as()) { return get(ident->name, {}); } - if (const auto * lit = ast->As()) + if (const auto * lit = ast->as()) { if (lit->value.isNull()) return get("Null", {}); diff --git a/dbms/src/DataTypes/DataTypeFixedString.cpp b/dbms/src/DataTypes/DataTypeFixedString.cpp index 2a548cded09..d1a007e16d2 100644 --- a/dbms/src/DataTypes/DataTypeFixedString.cpp +++ b/dbms/src/DataTypes/DataTypeFixedString.cpp @@ -273,7 +273,7 @@ static DataTypePtr create(const ASTPtr & arguments) if (!arguments || arguments->children.size() != 1) throw Exception("FixedString data type family must have exactly one argument - size in bytes", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - const auto * argument = arguments->children[0]->As(); + const auto * argument = arguments->children[0]->as(); if (!argument || argument->value.getType() != Field::Types::UInt64 || argument->value.get() == 0) throw Exception("FixedString data type family must have a number (positive integer) as its argument", ErrorCodes::UNEXPECTED_AST_STRUCTURE); diff --git a/dbms/src/DataTypes/DataTypeTuple.cpp b/dbms/src/DataTypes/DataTypeTuple.cpp index e4f2cba1e44..8f52b5fd3ff 100644 --- a/dbms/src/DataTypes/DataTypeTuple.cpp +++ b/dbms/src/DataTypes/DataTypeTuple.cpp @@ -531,7 +531,7 @@ static DataTypePtr create(const ASTPtr & arguments) for (const ASTPtr & child : arguments->children) { - if (const auto * name_and_type_pair = child->As()) + if (const auto * name_and_type_pair = child->as()) { nested_types.emplace_back(DataTypeFactory::instance().get(name_and_type_pair->type)); names.emplace_back(name_and_type_pair->name); diff --git a/dbms/src/DataTypes/DataTypesDecimal.cpp b/dbms/src/DataTypes/DataTypesDecimal.cpp index 509f613defb..8ec5bb6664f 100644 --- a/dbms/src/DataTypes/DataTypesDecimal.cpp +++ b/dbms/src/DataTypes/DataTypesDecimal.cpp @@ -208,8 +208,8 @@ static DataTypePtr create(const ASTPtr & arguments) throw Exception("Decimal data type family must have exactly two arguments: precision and scale", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - const auto * precision = arguments->children[0]->As(); - const auto * scale = arguments->children[1]->As(); + const auto * precision = arguments->children[0]->as(); + const auto * scale = arguments->children[1]->as(); if (!precision || precision->value.getType() != Field::Types::UInt64 || !scale || !(scale->value.getType() == Field::Types::Int64 || scale->value.getType() == Field::Types::UInt64)) @@ -228,7 +228,7 @@ static DataTypePtr createExect(const ASTPtr & arguments) throw Exception("Decimal data type family must have exactly two arguments: precision and scale", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - const auto * scale_arg = arguments->children[0]->As(); + const auto * scale_arg = arguments->children[0]->as(); if (!scale_arg || !(scale_arg->value.getType() == Field::Types::Int64 || scale_arg->value.getType() == Field::Types::UInt64)) throw Exception("Decimal data type family must have a two numbers as its arguments", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); diff --git a/dbms/src/Databases/DatabaseOrdinary.cpp b/dbms/src/Databases/DatabaseOrdinary.cpp index 1bed40e8e56..235cc3b6b51 100644 --- a/dbms/src/Databases/DatabaseOrdinary.cpp +++ b/dbms/src/Databases/DatabaseOrdinary.cpp @@ -370,7 +370,7 @@ static ASTPtr getCreateQueryFromMetadata(const String & metadata_path, const Str if (ast) { - auto * ast_create_query = ast->As(); + auto * ast_create_query = ast->as(); ast_create_query->attach = false; ast_create_query->database = database; } @@ -415,7 +415,7 @@ void DatabaseOrdinary::renameTable( ASTPtr ast = getQueryFromMetadata(detail::getTableMetadataPath(metadata_path, table_name)); if (!ast) throw Exception("There is no metadata file for table " + table_name, ErrorCodes::FILE_DOESNT_EXIST); - ast->As()->table = to_table_name; + ast->as()->table = to_table_name; /// NOTE Non-atomic. to_database_concrete->createTable(context, to_table_name, table, ast); @@ -533,7 +533,7 @@ void DatabaseOrdinary::alterTable( ParserCreateQuery parser; ASTPtr ast = parseQuery(parser, statement.data(), statement.data() + statement.size(), "in file " + table_metadata_path, 0); - const auto * ast_create_query = ast->As(); + const auto * ast_create_query = ast->as(); ASTPtr new_columns = InterpreterCreateQuery::formatColumns(columns); ASTPtr new_indices = InterpreterCreateQuery::formatIndices(indices); diff --git a/dbms/src/Databases/DatabasesCommon.cpp b/dbms/src/Databases/DatabasesCommon.cpp index 714a34461ad..33d343a6c05 100644 --- a/dbms/src/Databases/DatabasesCommon.cpp +++ b/dbms/src/Databases/DatabasesCommon.cpp @@ -26,7 +26,7 @@ namespace ErrorCodes String getTableDefinitionFromCreateQuery(const ASTPtr & query) { ASTPtr query_clone = query->clone(); - auto * create = query_clone->As(); + auto * create = query_clone->as(); /// We remove everything that is not needed for ATTACH from the query. create->attach = true; @@ -61,7 +61,7 @@ std::pair createTableFromDefinition( ParserCreateQuery parser; ASTPtr ast = parseQuery(parser, definition.data(), definition.data() + definition.size(), description_for_error_message, 0); - auto * ast_create_query = ast->As(); + auto * ast_create_query = ast->as(); ast_create_query->attach = true; ast_create_query->database = database_name; diff --git a/dbms/src/Interpreters/ActionsVisitor.cpp b/dbms/src/Interpreters/ActionsVisitor.cpp index 4ed853adc5d..5191e86c57e 100644 --- a/dbms/src/Interpreters/ActionsVisitor.cpp +++ b/dbms/src/Interpreters/ActionsVisitor.cpp @@ -84,7 +84,7 @@ SetPtr makeExplicitSet( auto getTupleTypeFromAst = [&context](const ASTPtr & tuple_ast) -> DataTypePtr { - const auto * func = tuple_ast->As(); + const auto * func = tuple_ast->as(); if (func && func->name == "tuple" && !func->arguments->children.empty()) { /// Won't parse all values of outer tuple. @@ -122,7 +122,7 @@ SetPtr makeExplicitSet( /// 1 in (1, 2); (1, 2) in ((1, 2), (3, 4)); etc. else if (left_tuple_depth + 1 == right_tuple_depth) { - const auto * set_func = right_arg->As(); + const auto * set_func = right_arg->as(); if (!set_func || set_func->name != "tuple") throw Exception("Incorrect type of 2nd argument for function " + node->name @@ -263,10 +263,10 @@ void ActionsVisitor::visit(const ASTPtr & ast) }; /// If the result of the calculation already exists in the block. - if ((ast->As() || ast->As()) && actions_stack.getSampleBlock().has(getColumnName())) + if ((ast->as() || ast->as()) && actions_stack.getSampleBlock().has(getColumnName())) return; - if (const auto * identifier = ast->As()) + if (const auto * identifier = ast->as()) { if (!only_consts && !actions_stack.getSampleBlock().has(getColumnName())) { @@ -287,7 +287,7 @@ void ActionsVisitor::visit(const ASTPtr & ast) actions_stack.addAction(ExpressionAction::addAliases({{identifier->name, identifier->alias}})); } } - else if (const auto * node = ast->As()) + else if (const auto * node = ast->as()) { if (node->name == "lambda") throw Exception("Unexpected lambda expression", ErrorCodes::UNEXPECTED_EXPRESSION); @@ -382,14 +382,14 @@ void ActionsVisitor::visit(const ASTPtr & ast) auto & child = node->arguments->children[arg]; auto child_column_name = child->getColumnName(); - const auto * lambda = child->As(); + const auto * lambda = child->as(); if (lambda && lambda->name == "lambda") { /// If the argument is a lambda expression, just remember its approximate type. if (lambda->arguments->children.size() != 2) throw Exception("lambda requires two arguments", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - const auto * lambda_args_tuple = lambda->arguments->children.at(0)->As(); + const auto * lambda_args_tuple = lambda->arguments->children.at(0)->as(); if (!lambda_args_tuple || lambda_args_tuple->name != "tuple") throw Exception("First argument of lambda must be a tuple", ErrorCodes::TYPE_MISMATCH); @@ -453,11 +453,11 @@ void ActionsVisitor::visit(const ASTPtr & ast) { ASTPtr child = node->arguments->children[i]; - const auto * lambda = child->As(); + const auto * lambda = child->as(); if (lambda && lambda->name == "lambda") { const DataTypeFunction * lambda_type = typeid_cast(argument_types[i].get()); - const auto * lambda_args_tuple = lambda->arguments->children.at(0)->As(); + const auto * lambda_args_tuple = lambda->arguments->children.at(0)->as(); const ASTs & lambda_arg_asts = lambda_args_tuple->arguments->children; NamesAndTypesList lambda_arguments; @@ -516,7 +516,7 @@ void ActionsVisitor::visit(const ASTPtr & ast) ExpressionAction::applyFunction(function_builder, argument_names, getColumnName())); } } - else if (const auto * literal = ast->As()) + else if (const auto * literal = ast->as()) { DataTypePtr type = applyVisitor(FieldToDataType(), literal->value); @@ -532,7 +532,7 @@ void ActionsVisitor::visit(const ASTPtr & ast) for (auto & child : ast->children) { /// Do not go to FROM, JOIN, UNION. - if (!child->As() && !child->As()) + if (!child->as() && !child->as()) visit(child); } } @@ -548,8 +548,8 @@ SetPtr ActionsVisitor::makeSet(const ASTFunction * node, const Block & sample_bl const ASTPtr & arg = args.children.at(1); /// If the subquery or table name for SELECT. - const auto * identifier = arg->As(); - if (arg->As() || identifier) + const auto * identifier = arg->as(); + if (arg->as() || identifier) { auto set_key = PreparedSetKey::forSubquery(*arg); if (prepared_sets.count(set_key)) diff --git a/dbms/src/Interpreters/AnalyzedJoin.cpp b/dbms/src/Interpreters/AnalyzedJoin.cpp index 3bcab24d6af..d674432bb10 100644 --- a/dbms/src/Interpreters/AnalyzedJoin.cpp +++ b/dbms/src/Interpreters/AnalyzedJoin.cpp @@ -45,7 +45,7 @@ ExpressionActionsPtr AnalyzedJoin::createJoinedBlockActions( if (!join) return nullptr; - const auto * join_params = join->table_join->As(); + const auto * join_params = join->table_join->as(); /// Create custom expression list with join keys from right table. auto expression_list = std::make_shared(); diff --git a/dbms/src/Interpreters/ArrayJoinedColumnsVisitor.h b/dbms/src/Interpreters/ArrayJoinedColumnsVisitor.h index 64737630537..204e4324c53 100644 --- a/dbms/src/Interpreters/ArrayJoinedColumnsVisitor.h +++ b/dbms/src/Interpreters/ArrayJoinedColumnsVisitor.h @@ -40,10 +40,10 @@ public: static bool needChildVisit(ASTPtr & node, const ASTPtr & child) { - if (node->As()) + if (node->as()) return false; - if (child->As() || child->As()) + if (child->as() || child->as()) return false; return true; @@ -51,9 +51,9 @@ public: static void visit(ASTPtr & ast, Data & data) { - if (const auto * t = ast->As()) + if (const auto * t = ast->as()) visit(*t, ast, data); - if (const auto * t = ast->As()) + if (const auto * t = ast->as()) visit(*t, ast, data); } @@ -72,7 +72,7 @@ private: const String nested_table_name = ast->getColumnName(); const String nested_table_alias = ast->getAliasOrColumnName(); - if (nested_table_alias == nested_table_name && !ast->As()) + if (nested_table_alias == nested_table_name && !ast->as()) throw Exception("No alias for non-trivial value in ARRAY JOIN: " + nested_table_name, ErrorCodes::ALIAS_REQUIRED); if (data.array_join_alias_to_name.count(nested_table_alias) || data.aliases.count(nested_table_alias)) diff --git a/dbms/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp b/dbms/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp index 644260b6a7d..0a1243758cf 100644 --- a/dbms/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp +++ b/dbms/src/Interpreters/ClusterProxy/SelectStreamFactory.cpp @@ -98,7 +98,7 @@ void SelectStreamFactory::createForShard( if (table_func_ptr) { - const auto * table_function = table_func_ptr->As(); + const auto * table_function = table_func_ptr->as(); main_table_storage = TableFunctionFactory::instance().get(table_function->name, context)->execute(table_func_ptr, context); } else diff --git a/dbms/src/Interpreters/Context.cpp b/dbms/src/Interpreters/Context.cpp index 03da9e0d2a5..c617a71912c 100644 --- a/dbms/src/Interpreters/Context.cpp +++ b/dbms/src/Interpreters/Context.cpp @@ -892,7 +892,7 @@ StoragePtr Context::executeTableFunction(const ASTPtr & table_expression) if (!res) { - TableFunctionPtr table_function_ptr = TableFunctionFactory::instance().get(table_expression->As()->name, *this); + TableFunctionPtr table_function_ptr = TableFunctionFactory::instance().get(table_expression->as()->name, *this); /// Run it and remember the result res = table_function_ptr->execute(table_expression, *this); diff --git a/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp b/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp index d601de3f403..b5413ccd0ac 100644 --- a/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp +++ b/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp @@ -41,7 +41,7 @@ public: for (auto & child : node.arguments->children) { - if (const auto * func = child->As()) + if (const auto * func = child->as()) { if (func->name == "and") flat_ands = false; @@ -92,8 +92,8 @@ private: if (node.arguments->children.size() != 2) return false; - const auto * left = node.arguments->children[0]->As(); - const auto * right = node.arguments->children[1]->As(); + const auto * left = node.arguments->children[0]->as(); + const auto * right = node.arguments->children[1]->as(); if (!left || !right) return false; @@ -146,7 +146,7 @@ static ASTPtr getCrossJoin(ASTSelectQuery & select, std::vectorAs(); + const auto * tables = select.tables->as(); if (!tables) return {}; @@ -154,12 +154,12 @@ static ASTPtr getCrossJoin(ASTSelectQuery & select, std::vectorchildren[0]->As(); - const auto * right = tables->children[1]->As(); + const auto * left = tables->children[0]->as(); + const auto * right = tables->children[1]->as(); if (!left || !right || !right->table_join) return {}; - if (const auto * join = right->table_join->As()) + if (const auto * join = right->table_join->as()) { if (join->kind == ASTTableJoin::Kind::Cross || join->kind == ASTTableJoin::Kind::Comma) @@ -167,8 +167,8 @@ static ASTPtr getCrossJoin(ASTSelectQuery & select, std::vectorchildren.empty()) throw Exception("Logical error: CROSS JOIN has expressions", ErrorCodes::LOGICAL_ERROR); - const auto * left_expr = left->table_expression->As(); - const auto * right_expr = right->table_expression->As(); + const auto * left_expr = left->table_expression->as(); + const auto * right_expr = right->table_expression->as(); table_names.reserve(2); if (extractTableName(*left_expr, table_names) && @@ -183,7 +183,7 @@ static ASTPtr getCrossJoin(ASTSelectQuery & select, std::vectorAs()) + if (auto * t = ast->as()) visit(*t, ast, data); } @@ -205,7 +205,7 @@ void CrossToInnerJoinMatcher::visit(ASTSelectQuery & select, ASTPtr & ast, Data if (visitor_data.matchAny()) { - auto * join = ast_join->As(); + auto * join = ast_join->as(); join->kind = ASTTableJoin::Kind::Inner; join->strictness = ASTTableJoin::Strictness::All; diff --git a/dbms/src/Interpreters/DDLWorker.cpp b/dbms/src/Interpreters/DDLWorker.cpp index b71e80c4189..f7d95f2e68d 100644 --- a/dbms/src/Interpreters/DDLWorker.cpp +++ b/dbms/src/Interpreters/DDLWorker.cpp @@ -613,7 +613,7 @@ void DDLWorker::processTask(DDLTask & task, const ZooKeeperPtr & zookeeper) String rewritten_query = queryToString(rewritten_ast); LOG_DEBUG(log, "Executing query: " << rewritten_query); - if (const auto * ast_alter = rewritten_ast->As()) + if (const auto * ast_alter = rewritten_ast->as()) { processTaskAlter(task, ast_alter, rewritten_query, task.entry_path, zookeeper); } @@ -1222,7 +1222,7 @@ BlockIO executeDDLQueryOnCluster(const ASTPtr & query_ptr_, const Context & cont if (!context.getSettingsRef().allow_distributed_ddl) throw Exception("Distributed DDL queries are prohibited for the user", ErrorCodes::QUERY_IS_PROHIBITED); - if (const auto * query_alter = query_ptr->As()) + if (const auto * query_alter = query_ptr->as()) { for (const auto & command : query_alter->command_list->commands) { diff --git a/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp b/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp index 2d5e85cee2c..e51ab1a7e77 100644 --- a/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp +++ b/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp @@ -27,7 +27,7 @@ DatabaseAndTableWithAlias::DatabaseAndTableWithAlias(const ASTIdentifier & ident DatabaseAndTableWithAlias::DatabaseAndTableWithAlias(const ASTPtr & node, const String & current_database) { - const auto * identifier = node->As(); + const auto * identifier = node->as(); if (!identifier) throw Exception("Logical error: identifier expected", ErrorCodes::LOGICAL_ERROR); @@ -78,10 +78,10 @@ std::vector getSelectTablesExpression(const ASTSelec for (const auto & child : select_query.tables->children) { - const auto * tables_element = child->As(); + const auto * tables_element = child->as(); if (tables_element->table_expression) - tables_expression.emplace_back(tables_element->table_expression->As()); + tables_expression.emplace_back(tables_element->table_expression->as()); } return tables_expression; @@ -92,16 +92,16 @@ static const ASTTableExpression * getTableExpression(const ASTSelectQuery & sele if (!select.tables) return {}; - const auto * tables_in_select_query = select.tables->As(); + const auto * tables_in_select_query = select.tables->as(); if (tables_in_select_query->children.size() <= table_number) return {}; - const auto * tables_element = tables_in_select_query->children[table_number]->As(); + const auto * tables_element = tables_in_select_query->children[table_number]->as(); if (!tables_element->table_expression) return {}; - return tables_element->table_expression->As(); + return tables_element->table_expression->as(); } std::vector getDatabaseAndTables(const ASTSelectQuery & select_query, const String & current_database) @@ -124,7 +124,7 @@ std::optional getDatabaseAndTable(const ASTSelectQuer return {}; ASTPtr database_and_table_name = table_expression->database_and_table_name; - if (!database_and_table_name || !database_and_table_name->As()) + if (!database_and_table_name || !database_and_table_name->as()) return {}; return DatabaseAndTableWithAlias(database_and_table_name); diff --git a/dbms/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp b/dbms/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp index 0e97595d47c..57a08994426 100644 --- a/dbms/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp +++ b/dbms/src/Interpreters/ExecuteScalarSubqueriesVisitor.cpp @@ -41,17 +41,17 @@ static ASTPtr addTypeConversion(std::unique_ptr && ast, const String bool ExecuteScalarSubqueriesMatcher::needChildVisit(ASTPtr & node, const ASTPtr & child) { /// Processed - if (node->As() || node->As()) + if (node->as() || node->as()) return false; /// Don't descend into subqueries in FROM section - if (node->As()) + if (node->as()) return false; - if (node->As()) + if (node->as()) { /// Do not go to FROM, JOIN, UNION. - if (child->As() || child->As()) + if (child->as() || child->as()) return false; } @@ -60,9 +60,9 @@ bool ExecuteScalarSubqueriesMatcher::needChildVisit(ASTPtr & node, const ASTPtr void ExecuteScalarSubqueriesMatcher::visit(ASTPtr & ast, Data & data) { - if (const auto * t = ast->As()) + if (const auto * t = ast->as()) visit(*t, ast, data); - if (const auto * t = ast->As()) + if (const auto * t = ast->as()) visit(*t, ast, data); } @@ -145,7 +145,7 @@ void ExecuteScalarSubqueriesMatcher::visit(const ASTFunction & func, ASTPtr & as out.push_back(&child); else for (size_t i = 0, size = func.arguments->children.size(); i < size; ++i) - if (i != 1 || !func.arguments->children[i]->As()) + if (i != 1 || !func.arguments->children[i]->as()) out.push_back(&func.arguments->children[i]); } } diff --git a/dbms/src/Interpreters/ExpressionAnalyzer.cpp b/dbms/src/Interpreters/ExpressionAnalyzer.cpp index 68b8526a959..85cc88de2d7 100644 --- a/dbms/src/Interpreters/ExpressionAnalyzer.cpp +++ b/dbms/src/Interpreters/ExpressionAnalyzer.cpp @@ -128,7 +128,7 @@ void ExpressionAnalyzer::analyzeAggregation() * Everything below (compiling temporary ExpressionActions) - only for the purpose of query analysis (type output). */ - auto * select_query = query->As(); + auto * select_query = query->as(); if (select_query && (select_query->group_expression_list || select_query->having_expression)) has_aggregation = true; @@ -149,7 +149,7 @@ void ExpressionAnalyzer::analyzeAggregation() const ASTTablesInSelectQueryElement * join = select_query->join(); if (join) { - const auto * table_join = join->table_join->As(); + const auto * table_join = join->table_join->as(); if (table_join->using_expression_list) getRootActions(table_join->using_expression_list, true, temp_actions); if (table_join->on_expression) @@ -250,7 +250,7 @@ void ExpressionAnalyzer::initGlobalSubqueriesAndExternalTables() void ExpressionAnalyzer::makeSetsForIndex() { - const auto * select_query = query->As(); + const auto * select_query = query->as(); if (storage && select_query && storage->supportsIndexForIn()) { @@ -290,18 +290,18 @@ void ExpressionAnalyzer::makeSetsForIndexImpl(const ASTPtr & node) for (auto & child : node->children) { /// Don't descend into subqueries. - if (child->As()) + if (child->as()) continue; /// Don't descend into lambda functions - const auto * func = child->As(); + const auto * func = child->as(); if (func && func->name == "lambda") continue; makeSetsForIndexImpl(child); } - const auto * func = node->As(); + const auto * func = node->as(); if (func && functionIsInOperator(func->name)) { const IAST & args = *func->arguments; @@ -309,7 +309,7 @@ void ExpressionAnalyzer::makeSetsForIndexImpl(const ASTPtr & node) if (storage && storage->mayBenefitFromIndexForIn(args.children.at(0), context)) { const ASTPtr & arg = args.children.at(1); - if (arg->As() || arg->As()) + if (arg->as() || arg->as()) { if (settings.use_index_for_in_with_subqueries) tryMakeSetForIndexFromSubquery(arg); @@ -367,7 +367,7 @@ void ExpressionAnalyzer::getActionsFromJoinKeys(const ASTTableJoin & table_join, void ExpressionAnalyzer::getAggregates(const ASTPtr & ast, ExpressionActionsPtr & actions) { - const auto * select_query = query->As(); + const auto * select_query = query->as(); /// There can not be aggregate functions inside the WHERE and PREWHERE. if (select_query && (ast.get() == select_query->where_expression.get() || ast.get() == select_query->prewhere_expression.get())) @@ -383,7 +383,7 @@ void ExpressionAnalyzer::getAggregates(const ASTPtr & ast, ExpressionActionsPtr return; } - const auto * node = ast->As(); + const auto * node = ast->as(); if (node && AggregateFunctionFactory::instance().isAggregateFunctionName(node->name)) { has_aggregation = true; @@ -418,7 +418,7 @@ void ExpressionAnalyzer::getAggregates(const ASTPtr & ast, ExpressionActionsPtr else { for (const auto & child : ast->children) - if (!child->As() && !child->As()) + if (!child->as() && !child->as()) getAggregates(child, actions); } } @@ -426,21 +426,21 @@ void ExpressionAnalyzer::getAggregates(const ASTPtr & ast, ExpressionActionsPtr void ExpressionAnalyzer::assertNoAggregates(const ASTPtr & ast, const char * description) { - const auto * node = ast->As(); + const auto * node = ast->as(); if (node && AggregateFunctionFactory::instance().isAggregateFunctionName(node->name)) throw Exception("Aggregate function " + node->getColumnName() + " is found " + String(description) + " in query", ErrorCodes::ILLEGAL_AGGREGATION); for (const auto & child : ast->children) - if (!child->As() && !child->As()) + if (!child->as() && !child->as()) assertNoAggregates(child, description); } void ExpressionAnalyzer::assertSelect() const { - const auto * select_query = query->As(); + const auto * select_query = query->as(); if (!select_query) throw Exception("Not a select query", ErrorCodes::LOGICAL_ERROR); @@ -479,7 +479,7 @@ void ExpressionAnalyzer::addMultipleArrayJoinAction(ExpressionActionsPtr & actio bool ExpressionAnalyzer::appendArrayJoin(ExpressionActionsChain & chain, bool only_types) { - const auto * select_query = query->As(); + const auto * select_query = query->as(); assertSelect(); @@ -526,7 +526,7 @@ static void appendRequiredColumns(NameSet & required_columns, const Block & samp bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_types) { - const auto * select_query = query->As(); + const auto * select_query = query->as(); assertSelect(); @@ -536,8 +536,8 @@ bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_ty initChain(chain, source_columns); ExpressionActionsChain::Step & step = chain.steps.back(); - const auto * join_element = select_query->join()->As(); - auto * join_params = join_element->table_join->As(); + const auto * join_element = select_query->join()->as(); + auto * join_params = join_element->table_join->as(); if (join_params->strictness == ASTTableJoin::Strictness::Unspecified && join_params->kind != ASTTableJoin::Kind::Cross) { @@ -549,7 +549,7 @@ bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_ty throw Exception("Expected ANY or ALL in JOIN section, because setting (join_default_strictness) is empty", DB::ErrorCodes::EXPECTED_ALL_OR_ANY); } - const auto * table_to_join = join_element->table_expression->As(); + const auto * table_to_join = join_element->table_expression->as(); getActionsFromJoinKeys(*join_params, only_types, step.actions); @@ -632,7 +632,7 @@ bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_ty bool ExpressionAnalyzer::appendPrewhere( ExpressionActionsChain & chain, bool only_types, const Names & additional_required_columns) { - const auto * select_query = query->As(); + const auto * select_query = query->as(); assertSelect(); @@ -707,7 +707,7 @@ bool ExpressionAnalyzer::appendPrewhere( bool ExpressionAnalyzer::appendWhere(ExpressionActionsChain & chain, bool only_types) { - const auto * select_query = query->As(); + const auto * select_query = query->as(); assertSelect(); @@ -727,7 +727,7 @@ bool ExpressionAnalyzer::appendWhere(ExpressionActionsChain & chain, bool only_t bool ExpressionAnalyzer::appendGroupBy(ExpressionActionsChain & chain, bool only_types) { - const auto * select_query = query->As(); + const auto * select_query = query->as(); assertAggregation(); @@ -749,7 +749,7 @@ bool ExpressionAnalyzer::appendGroupBy(ExpressionActionsChain & chain, bool only void ExpressionAnalyzer::appendAggregateFunctionsArguments(ExpressionActionsChain & chain, bool only_types) { - const auto * select_query = query->As(); + const auto * select_query = query->as(); assertAggregation(); @@ -775,7 +775,7 @@ void ExpressionAnalyzer::appendAggregateFunctionsArguments(ExpressionActionsChai bool ExpressionAnalyzer::appendHaving(ExpressionActionsChain & chain, bool only_types) { - const auto * select_query = query->As(); + const auto * select_query = query->as(); assertAggregation(); @@ -793,7 +793,7 @@ bool ExpressionAnalyzer::appendHaving(ExpressionActionsChain & chain, bool only_ void ExpressionAnalyzer::appendSelect(ExpressionActionsChain & chain, bool only_types) { - const auto * select_query = query->As(); + const auto * select_query = query->as(); assertSelect(); @@ -808,7 +808,7 @@ void ExpressionAnalyzer::appendSelect(ExpressionActionsChain & chain, bool only_ bool ExpressionAnalyzer::appendOrderBy(ExpressionActionsChain & chain, bool only_types) { - const auto * select_query = query->As(); + const auto * select_query = query->as(); assertSelect(); @@ -823,7 +823,7 @@ bool ExpressionAnalyzer::appendOrderBy(ExpressionActionsChain & chain, bool only ASTs asts = select_query->order_expression_list->children; for (size_t i = 0; i < asts.size(); ++i) { - const auto * ast = asts[i]->As(); + const auto * ast = asts[i]->as(); if (!ast || ast->children.size() < 1) throw Exception("Bad order expression AST", ErrorCodes::UNKNOWN_TYPE_OF_AST_NODE); ASTPtr order_expression = ast->children.at(0); @@ -835,7 +835,7 @@ bool ExpressionAnalyzer::appendOrderBy(ExpressionActionsChain & chain, bool only bool ExpressionAnalyzer::appendLimitBy(ExpressionActionsChain & chain, bool only_types) { - const auto * select_query = query->As(); + const auto * select_query = query->as(); assertSelect(); @@ -855,7 +855,7 @@ bool ExpressionAnalyzer::appendLimitBy(ExpressionActionsChain & chain, bool only void ExpressionAnalyzer::appendProjectResult(ExpressionActionsChain & chain) const { - const auto * select_query = query->As(); + const auto * select_query = query->as(); assertSelect(); @@ -890,7 +890,7 @@ void ExpressionAnalyzer::appendExpression(ExpressionActionsChain & chain, const void ExpressionAnalyzer::getActionsBeforeAggregation(const ASTPtr & ast, ExpressionActionsPtr & actions, bool no_subqueries) { - const auto * node = ast->As(); + const auto * node = ast->as(); if (node && AggregateFunctionFactory::instance().isAggregateFunctionName(node->name)) for (auto & argument : node->arguments->children) @@ -909,7 +909,7 @@ ExpressionActionsPtr ExpressionAnalyzer::getActions(bool add_aliases, bool proje ASTs asts; - if (const auto * node = query->As()) + if (const auto * node = query->as()) asts = node->children; else asts = ASTs(1, query); @@ -1025,7 +1025,7 @@ void ExpressionAnalyzer::collectUsedColumns() required.insert(column_name_type.name); } - const auto * select_query = query->As(); + const auto * select_query = query->as(); /// You need to read at least one column to find the number of rows. if (select_query && required.empty()) diff --git a/dbms/src/Interpreters/ExternalTablesVisitor.h b/dbms/src/Interpreters/ExternalTablesVisitor.h index 2c232ee4cbd..3ff5f38f84d 100644 --- a/dbms/src/Interpreters/ExternalTablesVisitor.h +++ b/dbms/src/Interpreters/ExternalTablesVisitor.h @@ -22,7 +22,7 @@ public: static void visit(ASTPtr & ast, Data & data) { - if (const auto * t = ast->As()) + if (const auto * t = ast->as()) visit(*t, ast, data); } diff --git a/dbms/src/Interpreters/GlobalSubqueriesVisitor.h b/dbms/src/Interpreters/GlobalSubqueriesVisitor.h index 07c7c6d084e..db56631061a 100644 --- a/dbms/src/Interpreters/GlobalSubqueriesVisitor.h +++ b/dbms/src/Interpreters/GlobalSubqueriesVisitor.h @@ -56,12 +56,12 @@ public: ASTPtr table_name; ASTPtr subquery_or_table_name; - if (subquery_or_table_name_or_table_expression->As()) + if (subquery_or_table_name_or_table_expression->as()) { table_name = subquery_or_table_name_or_table_expression; subquery_or_table_name = table_name; } - else if (const auto * ast_table_expr = subquery_or_table_name_or_table_expression->As()) + else if (const auto * ast_table_expr = subquery_or_table_name_or_table_expression->as()) { if (ast_table_expr->database_and_table_name) { @@ -74,7 +74,7 @@ public: subquery_or_table_name = subquery; } } - else if (subquery_or_table_name_or_table_expression->As()) + else if (subquery_or_table_name_or_table_expression->as()) { subquery = subquery_or_table_name_or_table_expression; subquery_or_table_name = subquery; @@ -115,7 +115,7 @@ public: auto database_and_table_name = createTableIdentifier("", external_table_name); - if (auto * ast_table_expr = subquery_or_table_name_or_table_expression->As()) + if (auto * ast_table_expr = subquery_or_table_name_or_table_expression->as()) { ast_table_expr->subquery.reset(); ast_table_expr->database_and_table_name = database_and_table_name; @@ -140,16 +140,16 @@ public: static void visit(ASTPtr & ast, Data & data) { - if (auto * t = ast->As()) + if (auto * t = ast->as()) visit(*t, ast, data); - if (auto * t = ast->As()) + if (auto * t = ast->as()) visit(*t, ast, data); } static bool needChildVisit(ASTPtr &, const ASTPtr & child) { /// We do not go into subqueries. - if (child->As()) + if (child->as()) return false; return true; } @@ -168,7 +168,7 @@ private: /// GLOBAL JOIN static void visit(ASTTablesInSelectQueryElement & table_elem, ASTPtr &, Data & data) { - if (table_elem.table_join && table_elem.table_join->As()->locality == ASTTableJoin::Locality::Global) + if (table_elem.table_join && table_elem.table_join->as()->locality == ASTTableJoin::Locality::Global) { data.addExternalStorage(table_elem.table_expression); data.has_global_subqueries = true; diff --git a/dbms/src/Interpreters/IdentifierSemantic.cpp b/dbms/src/Interpreters/IdentifierSemantic.cpp index 7ea2f8ac761..debc9ceccca 100644 --- a/dbms/src/Interpreters/IdentifierSemantic.cpp +++ b/dbms/src/Interpreters/IdentifierSemantic.cpp @@ -15,7 +15,7 @@ std::optional IdentifierSemantic::getColumnName(const ASTIdentifier & no std::optional IdentifierSemantic::getColumnName(const ASTPtr & ast) { if (ast) - if (const auto * id = ast->As()) + if (const auto * id = ast->as()) if (!id->semantic->special) return id->name; return {}; @@ -31,7 +31,7 @@ std::optional IdentifierSemantic::getTableName(const ASTIdentifier & nod std::optional IdentifierSemantic::getTableName(const ASTPtr & ast) { if (ast) - if (const auto * id = ast->As()) + if (const auto * id = ast->as()) if (id->semantic->special) return id->name; return {}; @@ -144,7 +144,7 @@ void IdentifierSemantic::setColumnLongName(ASTIdentifier & identifier, const Dat String IdentifierSemantic::columnNormalName(const ASTIdentifier & identifier, const DatabaseAndTableWithAlias & db_and_table) { ASTPtr copy = identifier.clone(); - setColumnNormalName(*copy->As(), db_and_table); + setColumnNormalName(*copy->as(), db_and_table); return copy->getAliasOrColumnName(); } diff --git a/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp b/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp index ce15eaf7683..556882b6774 100644 --- a/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp +++ b/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp @@ -30,7 +30,7 @@ namespace template void forEachNonGlobalSubquery(IAST * node, F && f) { - if (auto * function = node->As()) + if (auto * function = node->as()) { if (function->name == "in" || function->name == "notIn") { @@ -40,14 +40,14 @@ void forEachNonGlobalSubquery(IAST * node, F && f) /// Pass into other functions, as subquery could be in aggregate or in lambda functions. } - else if (const auto * join = node->As()) + else if (const auto * join = node->as()) { if (join->table_join && join->table_expression) { - auto * table_join = join->table_join->As(); + auto * table_join = join->table_join->as(); if (table_join->locality != ASTTableJoin::Locality::Global) { - auto & subquery = join->table_expression->As()->subquery; + auto & subquery = join->table_expression->as()->subquery; if (subquery) f(subquery.get(), nullptr, table_join); } @@ -59,7 +59,7 @@ void forEachNonGlobalSubquery(IAST * node, F && f) /// Descent into all children, but not into subqueries of other kind (scalar subqueries), that are irrelevant to us. for (auto & child : node->children) - if (!child->As()) + if (!child->as()) forEachNonGlobalSubquery(child.get(), f); } @@ -69,7 +69,7 @@ void forEachNonGlobalSubquery(IAST * node, F && f) template void forEachTable(IAST * node, F && f) { - if (auto * table_expression = node->As()) + if (auto * table_expression = node->as()) { auto & database_and_table = table_expression->database_and_table_name; if (database_and_table) @@ -103,15 +103,15 @@ void InJoinSubqueriesPreprocessor::process(ASTSelectQuery * query) const if (!query->tables) return; - const auto * tables_in_select_query = query->tables->As(); + const auto * tables_in_select_query = query->tables->as(); if (tables_in_select_query->children.empty()) return; - const auto * tables_element = tables_in_select_query->children[0]->As(); + const auto * tables_element = tables_in_select_query->children[0]->as(); if (!tables_element->table_expression) return; - const auto * table_expression = tables_element->table_expression->As(); + const auto * table_expression = tables_element->table_expression->as(); /// If not ordinary table, skip it. if (!table_expression->database_and_table_name) @@ -143,7 +143,7 @@ void InJoinSubqueriesPreprocessor::process(ASTSelectQuery * query) const { if (function) { - auto * concrete = function->As(); + auto * concrete = function->as(); if (concrete->name == "in") concrete->name = "globalIn"; @@ -157,7 +157,7 @@ void InJoinSubqueriesPreprocessor::process(ASTSelectQuery * query) const throw Exception("Logical error: unexpected function name " + concrete->name, ErrorCodes::LOGICAL_ERROR); } else if (table_join) - table_join->As()->locality = ASTTableJoin::Locality::Global; + table_join->as()->locality = ASTTableJoin::Locality::Global; else throw Exception("Logical error: unexpected AST node", ErrorCodes::LOGICAL_ERROR); } diff --git a/dbms/src/Interpreters/InterpreterAlterQuery.cpp b/dbms/src/Interpreters/InterpreterAlterQuery.cpp index e8075d84506..c51bceba2e0 100644 --- a/dbms/src/Interpreters/InterpreterAlterQuery.cpp +++ b/dbms/src/Interpreters/InterpreterAlterQuery.cpp @@ -30,7 +30,7 @@ InterpreterAlterQuery::InterpreterAlterQuery(const ASTPtr & query_ptr_, const Co BlockIO InterpreterAlterQuery::execute() { - const auto * alter = query_ptr->As(); + const auto * alter = query_ptr->as(); if (!alter->cluster.empty()) return executeDDLQueryOnCluster(query_ptr, context, {alter->database}); diff --git a/dbms/src/Interpreters/InterpreterCheckQuery.cpp b/dbms/src/Interpreters/InterpreterCheckQuery.cpp index 9caa33d57e9..1998ba897b2 100644 --- a/dbms/src/Interpreters/InterpreterCheckQuery.cpp +++ b/dbms/src/Interpreters/InterpreterCheckQuery.cpp @@ -19,7 +19,7 @@ InterpreterCheckQuery::InterpreterCheckQuery(const ASTPtr & query_ptr_, const Co BlockIO InterpreterCheckQuery::execute() { - const auto * alter = query_ptr->As(); + const auto * alter = query_ptr->as(); const String & table_name = alter->table; String database_name = alter->database.empty() ? context.getCurrentDatabase() : alter->database; diff --git a/dbms/src/Interpreters/InterpreterCreateQuery.cpp b/dbms/src/Interpreters/InterpreterCreateQuery.cpp index c881a4a2f49..01c2a691344 100644 --- a/dbms/src/Interpreters/InterpreterCreateQuery.cpp +++ b/dbms/src/Interpreters/InterpreterCreateQuery.cpp @@ -196,7 +196,7 @@ static ColumnsDeclarationAndModifiers parseColumns(const ASTExpressionList & col for (const auto & ast : column_list_ast.children) { - auto * col_decl = ast->As(); + auto * col_decl = ast->as(); DataTypePtr column_type = nullptr; if (col_decl->type) @@ -239,7 +239,7 @@ static ColumnsDeclarationAndModifiers parseColumns(const ASTExpressionList & col if (col_decl->comment) { - if (auto comment_str = col_decl->comment->As()->value.get(); !comment_str.empty()) + if (auto comment_str = col_decl->comment->as()->value.get(); !comment_str.empty()) comments.emplace(col_decl->name, comment_str); } } @@ -525,7 +525,7 @@ void InterpreterCreateQuery::setEngine(ASTCreateQuery & create) const String as_table_name = create.as_table; ASTPtr as_create_ptr = context.getCreateTableQuery(as_database_name, as_table_name); - const auto * as_create = as_create_ptr->As(); + const auto * as_create = as_create_ptr->as(); if (as_create->is_view) throw Exception( @@ -565,7 +565,7 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) { // Table SQL definition is available even if the table is detached auto query = context.getCreateTableQuery(database_name, table_name); - create = *query->As(); // Copy the saved create query, but use ATTACH instead of CREATE + create = *query->as(); // Copy the saved create query, but use ATTACH instead of CREATE create.attach = true; } @@ -682,7 +682,7 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) BlockIO InterpreterCreateQuery::execute() { - auto * create = query_ptr->As(); + auto * create = query_ptr->as(); checkAccess(*create); ASTQueryWithOutput::resetOutputASTIfExist(*create); diff --git a/dbms/src/Interpreters/InterpreterDescribeQuery.cpp b/dbms/src/Interpreters/InterpreterDescribeQuery.cpp index 302c73afe9f..5054c8e7274 100644 --- a/dbms/src/Interpreters/InterpreterDescribeQuery.cpp +++ b/dbms/src/Interpreters/InterpreterDescribeQuery.cpp @@ -58,7 +58,7 @@ Block InterpreterDescribeQuery::getSampleBlock() BlockInputStreamPtr InterpreterDescribeQuery::executeImpl() { - const auto * ast = query_ptr->As(); + const auto * ast = query_ptr->as(); NamesAndTypesList columns; ColumnDefaults column_defaults; @@ -66,7 +66,7 @@ BlockInputStreamPtr InterpreterDescribeQuery::executeImpl() ColumnCodecs column_codecs; StoragePtr table; - const auto * table_expression = ast->table_expression->As(); + const auto * table_expression = ast->table_expression->as(); if (table_expression->subquery) { @@ -76,7 +76,7 @@ BlockInputStreamPtr InterpreterDescribeQuery::executeImpl() { if (table_expression->table_function) { - const auto * table_function = table_expression->table_function->As(); + const auto * table_function = table_expression->table_function->as(); /// Get the table function TableFunctionPtr table_function_ptr = TableFunctionFactory::instance().get(table_function->name, context); /// Run it and remember the result @@ -84,7 +84,7 @@ BlockInputStreamPtr InterpreterDescribeQuery::executeImpl() } else { - const auto * identifier = table_expression->database_and_table_name->As(); + const auto * identifier = table_expression->database_and_table_name->as(); String database_name; String table_name; diff --git a/dbms/src/Interpreters/InterpreterDropQuery.cpp b/dbms/src/Interpreters/InterpreterDropQuery.cpp index cf3f6516505..7b10108bbf0 100644 --- a/dbms/src/Interpreters/InterpreterDropQuery.cpp +++ b/dbms/src/Interpreters/InterpreterDropQuery.cpp @@ -31,7 +31,7 @@ InterpreterDropQuery::InterpreterDropQuery(const ASTPtr & query_ptr_, Context & BlockIO InterpreterDropQuery::execute() { - auto * drop = query_ptr->As(); + auto * drop = query_ptr->as(); checkAccess(*drop); diff --git a/dbms/src/Interpreters/InterpreterExistsQuery.cpp b/dbms/src/Interpreters/InterpreterExistsQuery.cpp index 145577b292b..2d4d7a51437 100644 --- a/dbms/src/Interpreters/InterpreterExistsQuery.cpp +++ b/dbms/src/Interpreters/InterpreterExistsQuery.cpp @@ -32,7 +32,7 @@ Block InterpreterExistsQuery::getSampleBlock() BlockInputStreamPtr InterpreterExistsQuery::executeImpl() { - const auto * ast = query_ptr->As(); + const auto * ast = query_ptr->as(); bool res = ast->temporary ? context.isExternalTableExist(ast->table) : context.isTableExist(ast->database, ast->table); return std::make_shared(Block{{ diff --git a/dbms/src/Interpreters/InterpreterExplainQuery.cpp b/dbms/src/Interpreters/InterpreterExplainQuery.cpp index b939c8392af..28391d3eac8 100644 --- a/dbms/src/Interpreters/InterpreterExplainQuery.cpp +++ b/dbms/src/Interpreters/InterpreterExplainQuery.cpp @@ -39,7 +39,7 @@ Block InterpreterExplainQuery::getSampleBlock() BlockInputStreamPtr InterpreterExplainQuery::executeImpl() { - const auto * ast = query->As(); + const auto * ast = query->as(); Block sample_block = getSampleBlock(); MutableColumns res_columns = sample_block.cloneEmptyColumns(); diff --git a/dbms/src/Interpreters/InterpreterFactory.cpp b/dbms/src/Interpreters/InterpreterFactory.cpp index 0a5f12d8ee8..b2497481361 100644 --- a/dbms/src/Interpreters/InterpreterFactory.cpp +++ b/dbms/src/Interpreters/InterpreterFactory.cpp @@ -80,95 +80,95 @@ std::unique_ptr InterpreterFactory::get(ASTPtr & query, Context & { ProfileEvents::increment(ProfileEvents::Query); - if (query->As()) + if (query->as()) { /// This is internal part of ASTSelectWithUnionQuery. /// Even if there is SELECT without union, it is represented by ASTSelectWithUnionQuery with single ASTSelectQuery as a child. return std::make_unique(query, context, Names{}, stage); } - else if (query->As()) + else if (query->as()) { ProfileEvents::increment(ProfileEvents::SelectQuery); return std::make_unique(query, context, Names{}, stage); } - else if (query->As()) + else if (query->as()) { ProfileEvents::increment(ProfileEvents::InsertQuery); /// readonly is checked inside InterpreterInsertQuery bool allow_materialized = static_cast(context.getSettingsRef().insert_allow_materialized_columns); return std::make_unique(query, context, allow_materialized); } - else if (query->As()) + else if (query->as()) { /// readonly and allow_ddl are checked inside InterpreterCreateQuery return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { /// readonly and allow_ddl are checked inside InterpreterDropQuery return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { throwIfNoAccess(context); return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { /// readonly is checked inside InterpreterSetQuery return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { throwIfNoAccess(context); return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { throwIfNoAccess(context); return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { return std::make_unique(query, context); } - else if (query->As()) + else if (query->as()) { throwIfNoAccess(context); return std::make_unique(query, context); diff --git a/dbms/src/Interpreters/InterpreterInsertQuery.cpp b/dbms/src/Interpreters/InterpreterInsertQuery.cpp index f2791a360cf..14c385f344d 100644 --- a/dbms/src/Interpreters/InterpreterInsertQuery.cpp +++ b/dbms/src/Interpreters/InterpreterInsertQuery.cpp @@ -46,7 +46,7 @@ StoragePtr InterpreterInsertQuery::getTable(const ASTInsertQuery & query) { if (query.table_function) { - const auto * table_function = query.table_function->As(); + const auto * table_function = query.table_function->as(); const auto & factory = TableFunctionFactory::instance(); return factory.get(table_function->name, context)->execute(query.table_function, context); } @@ -92,7 +92,7 @@ Block InterpreterInsertQuery::getSampleBlock(const ASTInsertQuery & query, const BlockIO InterpreterInsertQuery::execute() { - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); checkAccess(*query); StoragePtr table = getTable(*query); @@ -171,7 +171,7 @@ void InterpreterInsertQuery::checkAccess(const ASTInsertQuery & query) std::pair InterpreterInsertQuery::getDatabaseTable() const { - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); return {query->database, query->table}; } diff --git a/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp b/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp index f3bcbb5010f..38b00e0b65f 100644 --- a/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp +++ b/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp @@ -172,7 +172,7 @@ public: BlockIO InterpreterKillQueryQuery::execute() { - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); if (!query->cluster.empty()) return executeDDLQueryOnCluster(query_ptr, context, {"system"}); @@ -261,7 +261,7 @@ BlockIO InterpreterKillQueryQuery::execute() Block InterpreterKillQueryQuery::getSelectResult(const String & columns, const String & table) { String select_query = "SELECT " + columns + " FROM " + table; - auto & where_expression = query_ptr->As()->where_expression; + auto & where_expression = query_ptr->as()->where_expression; if (where_expression) select_query += " WHERE " + queryToString(where_expression); diff --git a/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp b/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp index 2e22f7bd544..6d39ce3ee7a 100644 --- a/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp +++ b/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp @@ -17,7 +17,7 @@ namespace ErrorCodes BlockIO InterpreterOptimizeQuery::execute() { - const auto * ast = query_ptr->As(); + const auto * ast = query_ptr->as(); if (!ast->cluster.empty()) return executeDDLQueryOnCluster(query_ptr, context, {ast->database}); diff --git a/dbms/src/Interpreters/InterpreterRenameQuery.cpp b/dbms/src/Interpreters/InterpreterRenameQuery.cpp index 0ff1b545b1a..6cdd59ea68a 100644 --- a/dbms/src/Interpreters/InterpreterRenameQuery.cpp +++ b/dbms/src/Interpreters/InterpreterRenameQuery.cpp @@ -36,7 +36,7 @@ struct RenameDescription BlockIO InterpreterRenameQuery::execute() { - const auto * rename = query_ptr->As(); + const auto * rename = query_ptr->as(); if (!rename->cluster.empty()) { diff --git a/dbms/src/Interpreters/InterpreterSelectQuery.cpp b/dbms/src/Interpreters/InterpreterSelectQuery.cpp index 197a82640dd..44b8f85a932 100644 --- a/dbms/src/Interpreters/InterpreterSelectQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSelectQuery.cpp @@ -156,14 +156,14 @@ InterpreterSelectQuery::InterpreterSelectQuery( max_streams = settings.max_threads; - ASTPtr table_expression = extractTableExpression(*query_ptr->As(), 0); + ASTPtr table_expression = extractTableExpression(*query_ptr->as(), 0); bool is_table_func = false; bool is_subquery = false; if (table_expression) { - is_table_func = table_expression->As(); - is_subquery = table_expression->As(); + is_table_func = table_expression->as(); + is_subquery = table_expression->as(); } if (input) @@ -209,7 +209,7 @@ InterpreterSelectQuery::InterpreterSelectQuery( if (!only_analyze) { - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); if (query->sample_size() && (input || !storage || !storage->supportsSampling())) throw Exception("Illegal SAMPLE: table doesn't support sampling", ErrorCodes::SAMPLING_NOT_SUPPORTED); @@ -266,7 +266,7 @@ InterpreterSelectQuery::InterpreterSelectQuery( void InterpreterSelectQuery::getDatabaseAndTableNames(String & database_name, String & table_name) { - if (auto db_and_table = getDatabaseAndTable(*query_ptr->As(), 0)) + if (auto db_and_table = getDatabaseAndTable(*query_ptr->as(), 0)) { table_name = db_and_table->table; database_name = db_and_table->database; @@ -367,7 +367,7 @@ InterpreterSelectQuery::AnalysisResult InterpreterSelectQuery::analyzeExpression ExpressionActionsChain chain(context); Names additional_required_columns_after_prewhere; - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); if (storage && query->sample_size()) { @@ -508,7 +508,7 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt query_info.syntax_analyzer_result = syntax_analyzer_result; query_info.sets = query_analyzer->getPreparedSets(); - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); /// Try transferring some condition from WHERE to PREWHERE if enabled and viable if (settings.optimize_move_to_prewhere && query->where_expression && !query->prewhere_expression && !query->final()) @@ -553,7 +553,7 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt if (to_stage > QueryProcessingStage::FetchColumns) { /// Now we will compose block streams that perform the necessary actions. - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); /// Do I need to aggregate in a separate row rows that have not passed max_rows_to_group_by. bool aggregate_overflow_row = @@ -573,7 +573,7 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt { if (expressions.hasJoin()) { - const auto * join = query->join()->table_join->As(); + const auto * join = query->join()->table_join->as(); if (join->kind == ASTTableJoin::Kind::Full || join->kind == ASTTableJoin::Kind::Right) pipeline.stream_with_non_joined_data = expressions.before_join->createStreamWithNonJoinedDataIfFullOrRightJoin( pipeline.firstStream()->getHeader(), settings.max_block_size); @@ -943,7 +943,7 @@ void InterpreterSelectQuery::executeFetchColumns( } UInt64 max_block_size = settings.max_block_size; - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); auto [limit_length, limit_offset] = getLimitLengthAndOffset(*query, context); @@ -1080,7 +1080,7 @@ void InterpreterSelectQuery::executeWhere(Pipeline & pipeline, const ExpressionA { pipeline.transform([&](auto & stream) { stream = std::make_shared( - stream, expression, query_ptr->As()->where_expression->getColumnName(), remove_fiter); + stream, expression, query_ptr->as()->where_expression->getColumnName(), remove_fiter); }); } @@ -1208,7 +1208,7 @@ void InterpreterSelectQuery::executeHaving(Pipeline & pipeline, const Expression { pipeline.transform([&](auto & stream) { stream = std::make_shared( - stream, expression, query_ptr->As()->having_expression->getColumnName()); + stream, expression, query_ptr->as()->having_expression->getColumnName()); }); } @@ -1223,7 +1223,7 @@ void InterpreterSelectQuery::executeTotalsAndHaving(Pipeline & pipeline, bool ha pipeline.firstStream(), overflow_row, expression, - has_having ? query_ptr->As()->having_expression->getColumnName() : "", + has_having ? query_ptr->as()->having_expression->getColumnName() : "", settings.totals_mode, settings.totals_auto_threshold, final); @@ -1276,11 +1276,11 @@ static SortDescription getSortDescription(const ASTSelectQuery & query) for (const auto & elem : query.order_expression_list->children) { String name = elem->children.front()->getColumnName(); - const auto * order_by_elem = elem->As(); + const auto * order_by_elem = elem->as(); std::shared_ptr collator; if (order_by_elem->collation) - collator = std::make_shared(order_by_elem->collation->As()->value.get()); + collator = std::make_shared(order_by_elem->collation->as()->value.get()); order_descr.emplace_back(name, order_by_elem->direction, order_by_elem->nulls_direction, collator); } @@ -1291,7 +1291,7 @@ static SortDescription getSortDescription(const ASTSelectQuery & query) void InterpreterSelectQuery::executeOrder(Pipeline & pipeline) { - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); SortDescription order_descr = getSortDescription(*query); UInt64 limit = getLimitForSorting(*query, context); @@ -1324,7 +1324,7 @@ void InterpreterSelectQuery::executeOrder(Pipeline & pipeline) void InterpreterSelectQuery::executeMergeSorted(Pipeline & pipeline) { - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); SortDescription order_descr = getSortDescription(*query); UInt64 limit = getLimitForSorting(*query, context); @@ -1362,7 +1362,7 @@ void InterpreterSelectQuery::executeProjection(Pipeline & pipeline, const Expres void InterpreterSelectQuery::executeDistinct(Pipeline & pipeline, bool before_order, Names columns) { - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); if (query->distinct) { @@ -1406,7 +1406,7 @@ void InterpreterSelectQuery::executeUnion(Pipeline & pipeline) /// Preliminary LIMIT - is used in every source, if there are several sources, before they are combined. void InterpreterSelectQuery::executePreLimit(Pipeline & pipeline) { - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); /// If there is LIMIT if (query->limit_length) @@ -1422,7 +1422,7 @@ void InterpreterSelectQuery::executePreLimit(Pipeline & pipeline) void InterpreterSelectQuery::executeLimitBy(Pipeline & pipeline) { - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); if (!query->limit_by_value || !query->limit_by_expression_list) return; @@ -1451,10 +1451,10 @@ bool hasWithTotalsInAnySubqueryInFromClause(const ASTSelectQuery & query) if (auto query_table = extractTableExpression(query, 0)) { - if (const auto * ast_union = query_table->As()) + if (const auto * ast_union = query_table->as()) { for (const auto & elem : ast_union->list_of_selects->children) - if (hasWithTotalsInAnySubqueryInFromClause(*elem->As())) + if (hasWithTotalsInAnySubqueryInFromClause(*elem->as())) return true; } } @@ -1465,7 +1465,7 @@ bool hasWithTotalsInAnySubqueryInFromClause(const ASTSelectQuery & query) void InterpreterSelectQuery::executeLimit(Pipeline & pipeline) { - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); /// If there is LIMIT if (query->limit_length) @@ -1538,13 +1538,13 @@ void InterpreterSelectQuery::unifyStreams(Pipeline & pipeline) void InterpreterSelectQuery::ignoreWithTotals() { - query_ptr->As()->group_by_with_totals = false; + query_ptr->as()->group_by_with_totals = false; } void InterpreterSelectQuery::initSettings() { - if (auto settings = query_ptr->As()->settings) + if (auto settings = query_ptr->as()->settings) InterpreterSetQuery(settings, context).executeForCurrentContext(); } diff --git a/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp b/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp index 6add9f205a0..50fe7cd0fac 100644 --- a/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp @@ -36,7 +36,7 @@ InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery( to_stage(to_stage_), subquery_depth(subquery_depth_) { - const auto * ast = query_ptr->As(); + const auto * ast = query_ptr->as(); size_t num_selects = ast->list_of_selects->children.size(); diff --git a/dbms/src/Interpreters/InterpreterSetQuery.cpp b/dbms/src/Interpreters/InterpreterSetQuery.cpp index 2f7c97c0ea8..4dc80f07834 100644 --- a/dbms/src/Interpreters/InterpreterSetQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSetQuery.cpp @@ -16,7 +16,7 @@ namespace ErrorCodes BlockIO InterpreterSetQuery::execute() { - const auto * ast = query_ptr->As(); + const auto * ast = query_ptr->as(); checkAccess(*ast); @@ -61,7 +61,7 @@ void InterpreterSetQuery::checkAccess(const ASTSetQuery & ast) void InterpreterSetQuery::executeForCurrentContext() { - const auto * ast = query_ptr->As(); + const auto * ast = query_ptr->as(); checkAccess(*ast); diff --git a/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp b/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp index ed40035e5cc..625ca671a69 100644 --- a/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp +++ b/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp @@ -42,7 +42,7 @@ Block InterpreterShowCreateQuery::getSampleBlock() BlockInputStreamPtr InterpreterShowCreateQuery::executeImpl() { - const auto * ast = query_ptr->As(); + const auto * ast = query_ptr->as(); if (ast->temporary && !ast->database.empty()) throw Exception("Temporary databases are not possible.", ErrorCodes::SYNTAX_ERROR); diff --git a/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp b/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp index 0bc734e32ee..8214e56395f 100644 --- a/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp +++ b/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp @@ -25,7 +25,7 @@ InterpreterShowTablesQuery::InterpreterShowTablesQuery(const ASTPtr & query_ptr_ String InterpreterShowTablesQuery::getRewrittenQuery() { - const auto * query = query_ptr->As(); + const auto * query = query_ptr->as(); /// SHOW DATABASES if (query->databases) diff --git a/dbms/src/Interpreters/InterpreterSystemQuery.cpp b/dbms/src/Interpreters/InterpreterSystemQuery.cpp index 52220d2c911..7d01d058c31 100644 --- a/dbms/src/Interpreters/InterpreterSystemQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSystemQuery.cpp @@ -117,7 +117,7 @@ InterpreterSystemQuery::InterpreterSystemQuery(const ASTPtr & query_ptr_, Contex BlockIO InterpreterSystemQuery::execute() { - auto * query = query_ptr->As(); + auto * query = query_ptr->as(); using Type = ASTSystemQuery::Type; @@ -248,7 +248,7 @@ StoragePtr InterpreterSystemQuery::tryRestartReplica(const String & database_nam /// Attach actions { /// getCreateTableQuery must return canonical CREATE query representation, there are no need for AST postprocessing - auto * create = create_ast->As(); + auto * create = create_ast->as(); create->attach = true; std::string data_path = database->getDataPath(); diff --git a/dbms/src/Interpreters/InterpreterUseQuery.cpp b/dbms/src/Interpreters/InterpreterUseQuery.cpp index 484e4ac8600..2cd64ab985f 100644 --- a/dbms/src/Interpreters/InterpreterUseQuery.cpp +++ b/dbms/src/Interpreters/InterpreterUseQuery.cpp @@ -9,7 +9,7 @@ namespace DB BlockIO InterpreterUseQuery::execute() { - const String & new_database = query_ptr->As()->database; + const String & new_database = query_ptr->as()->database; context.getSessionContext().setCurrentDatabase(new_database); return {}; } diff --git a/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp b/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp index 5fd35270e5b..3fca3e3312d 100644 --- a/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp +++ b/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp @@ -90,17 +90,17 @@ struct ColumnAliasesMatcher static bool needChildVisit(ASTPtr & node, const ASTPtr &) { - if (node->As()) + if (node->as()) return false; return true; } static void visit(ASTPtr & ast, Data & data) { - if (auto * t = ast->As()) + if (auto * t = ast->as()) visit(*t, ast, data); - if (ast->As() || ast->As()) + if (ast->as() || ast->as()) throw Exception("Multiple JOIN do not support asterisks yet", ErrorCodes::NOT_IMPLEMENTED); } @@ -159,9 +159,9 @@ struct AppendSemanticVisitorData for (auto & child : select.select_expression_list->children) { - if (auto * node = child->As()) + if (auto * node = child->as()) AsteriskSemantic::setAliases(*node, rev_aliases); - if (auto * node = child->As()) + if (auto * node = child->as()) AsteriskSemantic::setAliases(*node, rev_aliases); } @@ -195,7 +195,7 @@ bool needRewrite(ASTSelectQuery & select) if (!select.tables) return false; - const auto * tables = select.tables->As(); + const auto * tables = select.tables->as(); if (!tables) return false; @@ -205,11 +205,11 @@ bool needRewrite(ASTSelectQuery & select) for (size_t i = 1; i < tables->children.size(); ++i) { - const auto * table = tables->children[i]->As(); + const auto * table = tables->children[i]->as(); if (!table || !table->table_join) throw Exception("Multiple JOIN expects joined tables", ErrorCodes::LOGICAL_ERROR); - const auto * join = table->table_join->As(); + const auto * join = table->table_join->as(); if (join->kind == ASTTableJoin::Kind::Comma) throw Exception("Multiple COMMA JOIN is not supported", ErrorCodes::NOT_IMPLEMENTED); @@ -232,7 +232,7 @@ using AppendSemanticVisitor = InDepthNodeVisitor; void JoinToSubqueryTransformMatcher::visit(ASTPtr & ast, Data & data) { - if (auto * t = ast->As()) + if (auto * t = ast->as()) visit(*t, ast, data); } @@ -260,10 +260,10 @@ void JoinToSubqueryTransformMatcher::visit(ASTSelectQuery & select, ASTPtr &, Da /// JOIN sections for (auto & child : select.tables->children) { - auto * table = child->As(); + auto * table = child->as(); if (table->table_join) { - auto * join = table->table_join->As(); + auto * join = table->table_join->as(); ColumnAliasesVisitor(aliases_data).visit(join->on_expression); } } @@ -305,8 +305,8 @@ static ASTPtr makeSubqueryTemplate() ASTPtr JoinToSubqueryTransformMatcher::replaceJoin(ASTPtr ast_left, ASTPtr ast_right) { - const auto * left = ast_left->As(); - const auto * right = ast_right->As(); + const auto * left = ast_left->as(); + const auto * right = ast_right->as(); if (!left || !right) throw Exception("Two TablesInSelectQueryElements expected", ErrorCodes::LOGICAL_ERROR); diff --git a/dbms/src/Interpreters/LogicalExpressionsOptimizer.cpp b/dbms/src/Interpreters/LogicalExpressionsOptimizer.cpp index 27a80242d96..b0ddd669d62 100644 --- a/dbms/src/Interpreters/LogicalExpressionsOptimizer.cpp +++ b/dbms/src/Interpreters/LogicalExpressionsOptimizer.cpp @@ -111,23 +111,23 @@ void LogicalExpressionsOptimizer::collectDisjunctiveEqualityChains() bool found_chain = false; - auto * function = to_node->As(); + auto * function = to_node->as(); if (function && function->name == "or" && function->children.size() == 1) { - const auto * expression_list = function->children[0]->As(); + const auto * expression_list = function->children[0]->as(); if (expression_list) { /// The chain of elements of the OR expression. for (auto & child : expression_list->children) { - auto * equals = child->As(); + auto * equals = child->as(); if (equals && equals->name == "equals" && equals->children.size() == 1) { - const auto * equals_expression_list = equals->children[0]->As(); + const auto * equals_expression_list = equals->children[0]->as(); if (equals_expression_list && equals_expression_list->children.size() == 2) { /// Equality expr = xN. - const auto * literal = equals_expression_list->children[1]->As(); + const auto * literal = equals_expression_list->children[1]->as(); if (literal) { auto expr_lhs = equals_expression_list->children[0]->getTreeHash(); @@ -157,7 +157,7 @@ void LogicalExpressionsOptimizer::collectDisjunctiveEqualityChains() { for (auto & child : to_node->children) { - if (!child->As()) + if (!child->as()) { if (!visited_nodes.count(child.get())) to_visit.push_back(Edge(to_node, &*child)); @@ -205,11 +205,11 @@ bool LogicalExpressionsOptimizer::mayOptimizeDisjunctiveEqualityChain(const Disj /// We check that the right-hand sides of all equalities have the same type. auto & first_operands = getFunctionOperands(equality_functions[0]); - const auto * first_literal = first_operands[1]->As(); + const auto * first_literal = first_operands[1]->as(); for (size_t i = 1; i < equality_functions.size(); ++i) { auto & operands = getFunctionOperands(equality_functions[i]); - const auto * literal = operands[1]->As(); + const auto * literal = operands[1]->as(); if (literal->value.getType() != first_literal->value.getType()) return false; @@ -237,8 +237,8 @@ void LogicalExpressionsOptimizer::addInExpression(const DisjunctiveEqualityChain /// Otherwise, they would be specified in the order of the ASTLiteral addresses, which is nondeterministic. std::sort(value_list->children.begin(), value_list->children.end(), [](const DB::ASTPtr & lhs, const DB::ASTPtr & rhs) { - const auto * val_lhs = lhs->As(); - const auto * val_rhs = rhs->As(); + const auto * val_lhs = lhs->as(); + const auto * val_rhs = rhs->as(); return val_lhs->value < val_rhs->value; }); diff --git a/dbms/src/Interpreters/OptimizeIfWithConstantConditionVisitor.cpp b/dbms/src/Interpreters/OptimizeIfWithConstantConditionVisitor.cpp index 26d62fe8bf3..dd63093493f 100644 --- a/dbms/src/Interpreters/OptimizeIfWithConstantConditionVisitor.cpp +++ b/dbms/src/Interpreters/OptimizeIfWithConstantConditionVisitor.cpp @@ -16,7 +16,7 @@ namespace ErrorCodes static bool tryExtractConstValueFromCondition(const ASTPtr & condition, bool & value) { /// numeric constant in condition - if (const auto * literal = condition->As()) + if (const auto * literal = condition->as()) { if (literal->value.getType() == Field::Types::Int64 || literal->value.getType() == Field::Types::UInt64) @@ -27,14 +27,14 @@ static bool tryExtractConstValueFromCondition(const ASTPtr & condition, bool & v } /// cast of numeric constant in condition to UInt8 - if (const auto * function = condition->As()) + if (const auto * function = condition->as()) { if (function->name == "CAST") { - if (const auto * expr_list = function->arguments->As()) + if (const auto * expr_list = function->arguments->as()) { const ASTPtr & type_ast = expr_list->children.at(1); - if (const auto * type_literal = type_ast->As()) + if (const auto * type_literal = type_ast->as()) { if (type_literal->value.getType() == Field::Types::String && type_literal->value.get() == "UInt8") @@ -54,7 +54,7 @@ void OptimizeIfWithConstantConditionVisitor::visit(ASTPtr & current_ast) for (ASTPtr & child : current_ast->children) { - auto * function_node = child->As(); + auto * function_node = child->as(); if (!function_node || function_node->name != "if") { visit(child); @@ -62,7 +62,7 @@ void OptimizeIfWithConstantConditionVisitor::visit(ASTPtr & current_ast) } visit(function_node->arguments); - const auto * args = function_node->arguments->As(); + const auto * args = function_node->arguments->as(); if (args->children.size() != 3) throw Exception("Wrong number of arguments for function 'if' (" + toString(args->children.size()) + " instead of 3)", diff --git a/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp b/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp index d6d3e4d0194..b564c2cd52d 100644 --- a/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp +++ b/dbms/src/Interpreters/PredicateExpressionsOptimizer.cpp @@ -151,7 +151,7 @@ std::vector PredicateExpressionsOptimizer::splitConjunctionPredicate(AST { const auto expression = predicate_expressions.at(idx); - if (const auto * function = expression->As()) + if (const auto * function = expression->as()) { if (function->name == and_function_name) { @@ -239,7 +239,7 @@ void PredicateExpressionsOptimizer::setNewAliasesForInnerPredicate( if (alias == qualified_name) { String name; - if (auto * id = ast->As()) + if (auto * id = ast->as()) { name = id->tryGetAlias(); if (name.empty()) @@ -260,7 +260,7 @@ void PredicateExpressionsOptimizer::setNewAliasesForInnerPredicate( bool PredicateExpressionsOptimizer::isArrayJoinFunction(const ASTPtr & node) { - if (const auto * function = node->As()) + if (const auto * function = node->as()) { if (function->name == "arrayJoin") return true; @@ -309,7 +309,7 @@ void PredicateExpressionsOptimizer::getSubqueryProjectionColumns(const ASTPtr & const ASTPtr & subselect = subquery->children[0]; ASTs select_with_union_projections; - const auto * select_with_union_query = subselect->As(); + const auto * select_with_union_query = subselect->as(); for (auto & select : select_with_union_query->list_of_selects->children) { @@ -325,7 +325,7 @@ void PredicateExpressionsOptimizer::getSubqueryProjectionColumns(const ASTPtr & subquery_projections.emplace_back(std::pair(select_projection_columns[i], qualified_name_prefix + select_with_union_projections[i]->getAliasOrColumnName())); - projection_columns.insert(std::pair(select->As(), subquery_projections)); + projection_columns.insert(std::pair(select->as(), subquery_projections)); } } } @@ -333,7 +333,7 @@ void PredicateExpressionsOptimizer::getSubqueryProjectionColumns(const ASTPtr & ASTs PredicateExpressionsOptimizer::getSelectQueryProjectionColumns(ASTPtr & ast) { ASTs projection_columns; - auto * select_query = ast->As(); + auto * select_query = ast->as(); /// first should normalize query tree. std::unordered_map aliases; @@ -352,7 +352,7 @@ ASTs PredicateExpressionsOptimizer::getSelectQueryProjectionColumns(ASTPtr & ast for (const auto & projection_column : select_query->select_expression_list->children) { - if (projection_column->As() || projection_column->As()) + if (projection_column->as() || projection_column->as()) { ASTs evaluated_columns = evaluateAsterisk(select_query, projection_column); @@ -375,7 +375,7 @@ ASTs PredicateExpressionsOptimizer::evaluateAsterisk(ASTSelectQuery * select_que std::vector tables_expression = getSelectTablesExpression(*select_query); - if (const auto * qualified_asterisk = asterisk->As()) + if (const auto * qualified_asterisk = asterisk->as()) { if (qualified_asterisk->children.size() != 1) throw Exception("Logical error: qualified asterisk must have exactly one child", ErrorCodes::LOGICAL_ERROR); @@ -399,8 +399,8 @@ ASTs PredicateExpressionsOptimizer::evaluateAsterisk(ASTSelectQuery * select_que { if (table_expression->subquery) { - const auto * subquery = table_expression->subquery->As(); - const auto * select_with_union_query = subquery->children[0]->As(); + const auto * subquery = table_expression->subquery->as(); + const auto * select_with_union_query = subquery->children[0]->as(); const auto subquery_projections = getSelectQueryProjectionColumns(select_with_union_query->list_of_selects->children[0]); projection_columns.insert(projection_columns.end(), subquery_projections.begin(), subquery_projections.end()); } @@ -415,7 +415,7 @@ ASTs PredicateExpressionsOptimizer::evaluateAsterisk(ASTSelectQuery * select_que } else if (table_expression->database_and_table_name) { - const auto * database_and_table_ast = table_expression->database_and_table_name->As(); + const auto * database_and_table_ast = table_expression->database_and_table_name->as(); DatabaseAndTableWithAlias database_and_table_name(*database_and_table_ast); storage = context.getTable(database_and_table_name.database, database_and_table_name.table); } diff --git a/dbms/src/Interpreters/ProcessList.cpp b/dbms/src/Interpreters/ProcessList.cpp index 1443c8d9db7..007d77c649e 100644 --- a/dbms/src/Interpreters/ProcessList.cpp +++ b/dbms/src/Interpreters/ProcessList.cpp @@ -38,7 +38,7 @@ static bool isUnlimitedQuery(const IAST * ast) return false; /// It is KILL QUERY - if (ast->As()) + if (ast->as()) return true; /// It is SELECT FROM system.processes @@ -46,12 +46,12 @@ static bool isUnlimitedQuery(const IAST * ast) /// False negative: USE system; SELECT * FROM processes; /// False positive: SELECT * FROM system.processes CROSS JOIN (SELECT ...) - if (const auto * ast_selects = ast->As()) + if (const auto * ast_selects = ast->as()) { if (!ast_selects->list_of_selects || ast_selects->list_of_selects->children.empty()) return false; - const auto * ast_select = ast_selects->list_of_selects->children[0]->As(); + const auto * ast_select = ast_selects->list_of_selects->children[0]->as(); if (!ast_select) return false; diff --git a/dbms/src/Interpreters/QueryAliasesVisitor.cpp b/dbms/src/Interpreters/QueryAliasesVisitor.cpp index aed03d52a08..f9257870583 100644 --- a/dbms/src/Interpreters/QueryAliasesVisitor.cpp +++ b/dbms/src/Interpreters/QueryAliasesVisitor.cpp @@ -32,16 +32,16 @@ static String wrongAliasMessage(const ASTPtr & ast, const ASTPtr & prev_ast, con bool QueryAliasesMatcher::needChildVisit(ASTPtr & node, const ASTPtr &) { /// Don't descent into table functions and subqueries and special case for ArrayJoin. - if (node->As() || node->As() || node->As()) + if (node->as() || node->as() || node->as()) return false; return true; } void QueryAliasesMatcher::visit(ASTPtr & ast, Data & data) { - if (auto * s = ast->As()) + if (auto * s = ast->as()) visit(*s, ast, data); - else if (auto * aj = ast->As()) + else if (auto * aj = ast->as()) visit(*aj, ast, data); else visitOther(ast, data); diff --git a/dbms/src/Interpreters/QueryNormalizer.cpp b/dbms/src/Interpreters/QueryNormalizer.cpp index 430a0fdd6b0..2ca8e010e2f 100644 --- a/dbms/src/Interpreters/QueryNormalizer.cpp +++ b/dbms/src/Interpreters/QueryNormalizer.cpp @@ -134,14 +134,14 @@ void QueryNormalizer::visit(ASTTablesInSelectQueryElement & node, const ASTPtr & /// mark table Identifiers as 'not a column' if (node.table_expression) { - auto * expr = node.table_expression->As(); + auto * expr = node.table_expression->as(); setIdentifierSpecial(expr->database_and_table_name); } /// normalize JOIN ON section if (node.table_join) { - auto * join = node.table_join->As(); + auto * join = node.table_join->as(); if (join->on_expression) visit(join->on_expression, data); } @@ -149,7 +149,7 @@ void QueryNormalizer::visit(ASTTablesInSelectQueryElement & node, const ASTPtr & static bool needVisitChild(const ASTPtr & child) { - if (child->As() || child->As()) + if (child->as() || child->as()) return false; return true; } @@ -177,7 +177,7 @@ void QueryNormalizer::visit(ASTSelectQuery & select, const ASTPtr & ast, Data & /// on aliases in expressions of the form 123 AS x, arrayMap(x -> 1, [2]). void QueryNormalizer::visitChildren(const ASTPtr & node, Data & data) { - if (const auto * func_node = node->As()) + if (const auto * func_node = node->as()) { /// We skip the first argument. We also assume that the lambda function can not have parameters. size_t first_pos = 0; @@ -194,7 +194,7 @@ void QueryNormalizer::visitChildren(const ASTPtr & node, Data & data) visit(child, data); } } - else if (!node->As()) + else if (!node->as()) { for (auto & child : node->children) if (needVisitChild(child)) @@ -225,13 +225,13 @@ void QueryNormalizer::visit(ASTPtr & ast, Data & data) data.current_alias = my_alias; } - if (auto * node = ast->As()) + if (auto * node = ast->as()) visit(*node, ast, data); - if (auto * node = ast->As()) + if (auto * node = ast->as()) visit(*node, ast, data); - if (auto * node = ast->As()) + if (auto * node = ast->as()) visit(*node, ast, data); - if (auto * node = ast->As()) + if (auto * node = ast->as()) visit(*node, ast, data); /// If we replace the root of the subtree, we will be called again for the new root, in case the alias is replaced by an alias. diff --git a/dbms/src/Interpreters/RequiredSourceColumnsVisitor.cpp b/dbms/src/Interpreters/RequiredSourceColumnsVisitor.cpp index 846196728da..f05cb6faa41 100644 --- a/dbms/src/Interpreters/RequiredSourceColumnsVisitor.cpp +++ b/dbms/src/Interpreters/RequiredSourceColumnsVisitor.cpp @@ -22,7 +22,7 @@ static std::vector extractNamesFromLambda(const ASTFunction & node) if (node.arguments->children.size() != 2) throw Exception("lambda requires two arguments", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); - const auto * lambda_args_tuple = node.arguments->children[0]->As(); + const auto * lambda_args_tuple = node.arguments->children[0]->as(); if (!lambda_args_tuple || lambda_args_tuple->name != "tuple") throw Exception("First argument of lambda must be a tuple", ErrorCodes::TYPE_MISMATCH); @@ -30,7 +30,7 @@ static std::vector extractNamesFromLambda(const ASTFunction & node) std::vector names; for (auto & child : lambda_args_tuple->arguments->children) { - const auto * identifier = child->As(); + const auto * identifier = child->as(); if (!identifier) throw Exception("lambda argument declarations must be identifiers", ErrorCodes::TYPE_MISMATCH); @@ -42,14 +42,14 @@ static std::vector extractNamesFromLambda(const ASTFunction & node) bool RequiredSourceColumnsMatcher::needChildVisit(ASTPtr & node, const ASTPtr & child) { - if (child->As()) + if (child->as()) return false; /// Processed. Do not need children. - if (node->As() || node->As() || node->As()) + if (node->as() || node->as() || node->as()) return false; - if (const auto * f = node->As()) + if (const auto * f = node->as()) { /// "indexHint" is a special function for index analysis. Everything that is inside it is not calculated. @sa KeyCondition /// "lambda" visit children itself. @@ -64,12 +64,12 @@ void RequiredSourceColumnsMatcher::visit(ASTPtr & ast, Data & data) { /// results are columns - if (auto * t = ast->As()) + if (auto * t = ast->as()) { visit(*t, ast, data); return; } - if (auto * t = ast->As()) + if (auto * t = ast->as()) { data.addColumnAliasIfAny(*ast); visit(*t, ast, data); @@ -78,24 +78,24 @@ void RequiredSourceColumnsMatcher::visit(ASTPtr & ast, Data & data) /// results are tables - if (auto * t = ast->As()) + if (auto * t = ast->as()) { visit(*t, ast, data); return; } - if (auto * t = ast->As()) + if (auto * t = ast->as()) { visit(*t, ast, data); return; } - if (auto * t = ast->As()) + if (auto * t = ast->as()) { data.addTableAliasIfAny(*ast); visit(*t, ast, data); return; } - if (ast->As()) + if (ast->as()) { data.addTableAliasIfAny(*ast); return; @@ -103,7 +103,7 @@ void RequiredSourceColumnsMatcher::visit(ASTPtr & ast, Data & data) /// other - if (auto * t = ast->As()) + if (auto * t = ast->as()) { data.has_array_join = true; visit(*t, ast, data); @@ -116,7 +116,7 @@ void RequiredSourceColumnsMatcher::visit(ASTSelectQuery & select, const ASTPtr & /// special case for top-level SELECT items: they are publics for (auto & node : select.select_expression_list->children) { - if (const auto * identifier = node->As()) + if (const auto * identifier = node->as()) data.addColumnIdentifier(*identifier); else data.addColumnAliasIfAny(*node); @@ -168,9 +168,9 @@ void RequiredSourceColumnsMatcher::visit(ASTTablesInSelectQueryElement & node, c for (auto & child : node.children) { - if (auto * e = child->As()) + if (auto * e = child->as()) expr = e; - if (auto * j = child->As()) + if (auto * j = child->as()) join = j; } @@ -205,7 +205,7 @@ void RequiredSourceColumnsMatcher::visit(const ASTArrayJoin & node, const ASTPtr { data.addArrayJoinAliasIfAny(*expr); - if (const auto * identifier = expr->As()) + if (const auto * identifier = expr->as()) { data.addArrayJoinIdentifier(*identifier); continue; diff --git a/dbms/src/Interpreters/Set.cpp b/dbms/src/Interpreters/Set.cpp index 2a8d52ec2d9..1eb97e3e0e3 100644 --- a/dbms/src/Interpreters/Set.cpp +++ b/dbms/src/Interpreters/Set.cpp @@ -207,11 +207,11 @@ bool Set::insertFromBlock(const Block & block) static Field extractValueFromNode(const ASTPtr & node, const IDataType & type, const Context & context) { - if (const auto * lit = node->As()) + if (const auto * lit = node->as()) { return convertFieldToType(lit->value, type); } - else if (node->As()) + else if (node->as()) { std::pair value_raw = evaluateConstantExpression(node, context); return convertFieldToType(value_raw.first, type, value_raw.second.get()); @@ -235,7 +235,7 @@ void Set::createFromAST(const DataTypes & types, ASTPtr node, const Context & co DataTypePtr tuple_type; Row tuple_values; - const auto * list = node->As(); + const auto * list = node->as(); for (auto & elem : list->children) { if (num_columns == 1) @@ -245,7 +245,7 @@ void Set::createFromAST(const DataTypes & types, ASTPtr node, const Context & co if (!value.isNull()) columns[0]->insert(value); } - else if (const auto * func = elem->As()) + else if (const auto * func = elem->as()) { Field function_result; const TupleBackend * tuple = nullptr; diff --git a/dbms/src/Interpreters/SyntaxAnalyzer.cpp b/dbms/src/Interpreters/SyntaxAnalyzer.cpp index a2342ee5587..d87be9b7bd0 100644 --- a/dbms/src/Interpreters/SyntaxAnalyzer.cpp +++ b/dbms/src/Interpreters/SyntaxAnalyzer.cpp @@ -112,12 +112,12 @@ void translateQualifiedNames(ASTPtr & query, const ASTSelectQuery & select_query bool hasArrayJoin(const ASTPtr & ast) { - if (const ASTFunction * function = ast->As()) + if (const ASTFunction * function = ast->as()) if (function->name == "arrayJoin") return true; for (const auto & child : ast->children) - if (!child->As() && hasArrayJoin(child)) + if (!child->as() && hasArrayJoin(child)) return true; return false; @@ -215,7 +215,7 @@ void optimizeGroupBy(ASTSelectQuery * select_query, const NameSet & source_colum const auto is_literal = [] (const ASTPtr & ast) -> bool { - return ast->As(); + return ast->as(); }; auto & group_exprs = select_query->group_expression_list->children; @@ -232,7 +232,7 @@ void optimizeGroupBy(ASTSelectQuery * select_query, const NameSet & source_colum /// iterate over each GROUP BY expression, eliminate injective function calls and literals for (size_t i = 0; i < group_exprs.size();) { - if (const auto * function = group_exprs[i]->As()) + if (const auto * function = group_exprs[i]->as()) { /// assert function is injective if (possibly_injective_function_names.count(function->name)) @@ -244,9 +244,9 @@ void optimizeGroupBy(ASTSelectQuery * select_query, const NameSet & source_colum continue; } - const auto & dict_name = function->arguments->children[0]->As()->value.safeGet(); + const auto & dict_name = function->arguments->children[0]->as()->value.safeGet(); const auto & dict_ptr = context.getExternalDictionaries().getDictionary(dict_name); - const auto & attr_name = function->arguments->children[1]->As()->value.safeGet(); + const auto & attr_name = function->arguments->children[1]->as()->value.safeGet(); if (!dict_ptr->isInjective(attr_name)) { @@ -324,7 +324,7 @@ void optimizeOrderBy(const ASTSelectQuery * select_query) for (const auto & elem : elems) { String name = elem->children.front()->getColumnName(); - const auto * order_by_elem = elem->As(); + const auto * order_by_elem = elem->as(); if (elems_set.emplace(name, order_by_elem->collation ? order_by_elem->collation->getColumnName() : "").second) unique_elems.emplace_back(elem); @@ -359,11 +359,11 @@ void optimizeLimitBy(const ASTSelectQuery * select_query) /// Remove duplicated columns from USING(...). void optimizeUsing(const ASTSelectQuery * select_query) { - const auto * node = select_query->join()->As(); + const auto * node = select_query->join()->as(); if (!node) return; - const auto * table_join = node->table_join->As(); + const auto * table_join = node->table_join->as(); if (!(table_join && table_join->using_expression_list)) return; @@ -406,7 +406,7 @@ void getArrayJoinedColumns(ASTPtr & query, SyntaxAnalyzerResult & result, const String result_name = expr->getAliasOrColumnName(); /// This is an array. - if (!expr->As() || source_columns_set.count(source_name)) + if (!expr->as() || source_columns_set.count(source_name)) { result.array_join_result_to_source[result_name] = source_name; } @@ -450,7 +450,7 @@ void collectJoinedColumnsFromJoinOnExpr(AnalyzedJoin & analyzed_join, const ASTT { if (IdentifierSemantic::getColumnName(ast)) { - const auto * identifier = ast->As(); + const auto * identifier = ast->as(); /// It's set in TranslateQualifiedNamesVisitor size_t membership = IdentifierSemantic::getMembership(*identifier); @@ -494,7 +494,7 @@ void collectJoinedColumnsFromJoinOnExpr(AnalyzedJoin & analyzed_join, const ASTT /// For equal expression find out corresponding table for each part, translate qualified names and add asts to join keys. auto add_columns_from_equals_expr = [&](const ASTPtr & expr) { - const auto * func_equals = expr->As(); + const auto * func_equals = expr->as(); if (!func_equals || func_equals->name != "equals") throwSyntaxException("Expected equals expression, got " + queryToString(expr) + "."); @@ -533,7 +533,7 @@ void collectJoinedColumnsFromJoinOnExpr(AnalyzedJoin & analyzed_join, const ASTT } }; - const auto * func = table_join.on_expression->As(); + const auto * func = table_join.on_expression->as(); if (func && func->name == "and") { for (const auto & expr : func->arguments->children) @@ -552,13 +552,13 @@ void collectJoinedColumns(AnalyzedJoin & analyzed_join, const ASTSelectQuery & s if (!node) return; - const auto * table_join = node->table_join->As(); - const auto * table_expression = node->table_expression->As(); + const auto * table_join = node->table_join->as(); + const auto * table_expression = node->table_expression->as(); DatabaseAndTableWithAlias joined_table_name(*table_expression, current_database); if (table_join->using_expression_list) { - const auto * keys = table_join->using_expression_list->As(); + const auto * keys = table_join->using_expression_list->as(); for (const auto & key : keys->children) analyzed_join.addUsingKey(key); @@ -594,10 +594,10 @@ void replaceJoinedTable(const ASTTablesInSelectQueryElement* join) if (!join || !join->table_expression) return; - const auto * table_expr = join->table_expression->As(); + const auto * table_expr = join->table_expression->as(); if (table_expr->database_and_table_name) { - const auto * table_id = table_expr->database_and_table_name->As(); + const auto * table_id = table_expr->database_and_table_name->as(); String expr = "(select * from " + table_id->name + ") as " + table_id->shortName(); // FIXME: since the expression "a as b" exposes both "a" and "b" names, which is not equivalent to "(select * from a) as b", @@ -606,7 +606,7 @@ void replaceJoinedTable(const ASTTablesInSelectQueryElement* join) if (table_id->alias.empty() && table_id->isShort()) { ParserTableExpression parser; - table_expr = parseQuery(parser, expr, 0)->As(); + table_expr = parseQuery(parser, expr, 0)->as(); } } } @@ -620,7 +620,7 @@ SyntaxAnalyzerResultPtr SyntaxAnalyzer::analyze( const Names & required_result_columns, StoragePtr storage) const { - auto * select_query = query->As(); + auto * select_query = query->as(); if (!storage && select_query) { if (auto db_and_table = getDatabaseAndTable(*select_query, 0)) @@ -651,7 +651,7 @@ SyntaxAnalyzerResultPtr SyntaxAnalyzer::analyze( if (settings.enable_optimize_predicate_expression) replaceJoinedTable(node); - const auto * joined_expression = node->table_expression->As(); + const auto * joined_expression = node->table_expression->as(); DatabaseAndTableWithAlias table(*joined_expression, context.getCurrentDatabase()); NamesAndTypesList joined_columns = getNamesAndTypeListFromTableExpression(*joined_expression, context); diff --git a/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp b/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp index 54f3455f14a..5bfd2897c6c 100644 --- a/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp +++ b/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp @@ -31,11 +31,11 @@ namespace ErrorCodes bool TranslateQualifiedNamesMatcher::needChildVisit(ASTPtr & node, const ASTPtr & child) { /// Do not go to FROM, JOIN, subqueries. - if (child->As() || child->As()) + if (child->as() || child->as()) return false; /// Processed nodes. Do not go into children. - if (node->As() || node->As()) + if (node->as() || node->as()) return false; /// ASTSelectQuery + others @@ -44,15 +44,15 @@ bool TranslateQualifiedNamesMatcher::needChildVisit(ASTPtr & node, const ASTPtr void TranslateQualifiedNamesMatcher::visit(ASTPtr & ast, Data & data) { - if (auto * t = ast->As()) + if (auto * t = ast->as()) visit(*t, ast, data); - if (auto * t = ast->As()) + if (auto * t = ast->as()) visit(*t, ast, data); - if (auto * t = ast->As()) + if (auto * t = ast->as()) visit(*t, ast, data); - if (auto * node = ast->As()) + if (auto * node = ast->as()) visit(*node, ast, data); - if (auto * node = ast->As()) + if (auto * node = ast->as()) visit(*node, ast, data); } @@ -89,7 +89,7 @@ void TranslateQualifiedNamesMatcher::visit(ASTFunction & node, const ASTPtr &, D String func_name_lowercase = Poco::toLower(node.name); if (func_name_lowercase == "count" && func_arguments->children.size() == 1 && - func_arguments->children[0]->As()) + func_arguments->children[0]->as()) func_arguments->children.clear(); } @@ -171,14 +171,14 @@ void TranslateQualifiedNamesMatcher::visit(ASTExpressionList & node, const ASTPt bool has_asterisk = false; for (const auto & child : node.children) { - if (child->As()) + if (child->as()) { if (tables_with_columns.empty()) throw Exception("An asterisk cannot be replaced with empty columns.", ErrorCodes::LOGICAL_ERROR); has_asterisk = true; break; } - else if (const auto * qa = child->As()) + else if (const auto * qa = child->as()) { visit(*qa, child, data); /// check if it's OK before rewrite has_asterisk = true; @@ -195,7 +195,7 @@ void TranslateQualifiedNamesMatcher::visit(ASTExpressionList & node, const ASTPt for (const auto & child : old_children) { - if (const auto * asterisk = child->As()) + if (const auto * asterisk = child->as()) { bool first_table = true; for (const auto & [table, table_columns] : tables_with_columns) @@ -212,7 +212,7 @@ void TranslateQualifiedNamesMatcher::visit(ASTExpressionList & node, const ASTPt first_table = false; } } - else if (const auto * qualified_asterisk = child->As()) + else if (const auto * qualified_asterisk = child->as()) { DatabaseAndTableWithAlias ident_db_and_name(qualified_asterisk->children[0]); @@ -237,15 +237,15 @@ void TranslateQualifiedNamesMatcher::visit(ASTExpressionList & node, const ASTPt /// 'select * from a join b using id' should result one 'id' column void TranslateQualifiedNamesMatcher::extractJoinUsingColumns(const ASTPtr ast, Data & data) { - const auto * table_join = ast->As(); + const auto * table_join = ast->as(); if (table_join->using_expression_list) { - const auto * keys = table_join->using_expression_list->As(); + const auto * keys = table_join->using_expression_list->as(); for (const auto & key : keys->children) if (auto opt_column = getIdentifierName(key)) data.join_using_columns.insert(*opt_column); - else if (key->As()) + else if (key->as()) data.join_using_columns.insert(key->getColumnName()); else { diff --git a/dbms/src/Interpreters/evaluateConstantExpression.cpp b/dbms/src/Interpreters/evaluateConstantExpression.cpp index 23030fed191..7fe92b6d907 100644 --- a/dbms/src/Interpreters/evaluateConstantExpression.cpp +++ b/dbms/src/Interpreters/evaluateConstantExpression.cpp @@ -60,11 +60,11 @@ std::pair> evaluateConstantExpression(co ASTPtr evaluateConstantExpressionAsLiteral(const ASTPtr & node, const Context & context) { /// Branch with string in query. - if (node->As()) + if (node->as()) return node; /// Branch with TableFunction in query. - if (const auto * table_func_ptr = node->As()) + if (const auto * table_func_ptr = node->as()) if (TableFunctionFactory::instance().isTableFunctionName(table_func_ptr->name)) return node; @@ -73,7 +73,7 @@ ASTPtr evaluateConstantExpressionAsLiteral(const ASTPtr & node, const Context & ASTPtr evaluateConstantExpressionOrIdentifierAsLiteral(const ASTPtr & node, const Context & context) { - if (const auto * id = node->As()) + if (const auto * id = node->as()) return std::make_shared(id->name); return evaluateConstantExpressionAsLiteral(node, context); @@ -145,8 +145,8 @@ namespace { const auto * left = fn->arguments->children.front().get(); const auto * right = fn->arguments->children.back().get(); - const auto * identifier = left->As() ? left->As() : right->As(); - const auto * literal = left->As() ? left->As() : right->As(); + const auto * identifier = left->as() ? left->as() : right->as(); + const auto * literal = left->as() ? left->as() : right->as(); return analyzeEquals(identifier, literal, expr); } @@ -154,15 +154,15 @@ namespace { const auto * left = fn->arguments->children.front().get(); const auto * right = fn->arguments->children.back().get(); - const auto * identifier = left->As(); - const auto * inner_fn = right->As(); + const auto * identifier = left->as(); + const auto * inner_fn = right->as(); if (!inner_fn) { return {}; } - const auto * tuple = inner_fn->children.front()->As(); + const auto * tuple = inner_fn->children.front()->as(); if (!tuple) { @@ -173,7 +173,7 @@ namespace for (const auto & child : tuple->children) { - const auto * literal = child->As(); + const auto * literal = child->as(); const auto dnf = analyzeEquals(identifier, literal, expr); if (dnf.empty()) @@ -188,7 +188,7 @@ namespace } else if (fn->name == "or") { - const auto * args = fn->children.front()->As(); + const auto * args = fn->children.front()->as(); if (!args) { @@ -199,7 +199,7 @@ namespace for (const auto & arg : args->children) { - const auto dnf = analyzeFunction(arg->As(), expr); + const auto dnf = analyzeFunction(arg->as(), expr); if (dnf.empty()) { @@ -213,7 +213,7 @@ namespace } else if (fn->name == "and") { - const auto * args = fn->children.front()->As(); + const auto * args = fn->children.front()->as(); if (!args) { @@ -224,7 +224,7 @@ namespace for (const auto & arg : args->children) { - const auto dnf = analyzeFunction(arg->As(), expr); + const auto dnf = analyzeFunction(arg->as(), expr); if (dnf.empty()) { @@ -247,7 +247,7 @@ std::optional evaluateExpressionOverConstantCondition(const ASTPtr & nod // TODO: `node` may be always-false literal. - if (const auto * fn = node->As()) + if (const auto * fn = node->as()) { const auto dnf = analyzeFunction(fn, target_expr); diff --git a/dbms/src/Interpreters/executeQuery.cpp b/dbms/src/Interpreters/executeQuery.cpp index adcfa1a0f17..87badd74ba4 100644 --- a/dbms/src/Interpreters/executeQuery.cpp +++ b/dbms/src/Interpreters/executeQuery.cpp @@ -171,7 +171,7 @@ static std::tuple executeQueryImpl( /// TODO Parser should fail early when max_query_size limit is reached. ast = parseQuery(parser, begin, end, "", max_query_size); - auto * insert_query = ast->As(); + auto * insert_query = ast->as(); if (insert_query && insert_query->data) { query_end = insert_query->data; @@ -226,7 +226,7 @@ static std::tuple executeQueryImpl( /// Put query to process list. But don't put SHOW PROCESSLIST query itself. ProcessList::EntryPtr process_list_entry; - if (!internal && !ast->As()) + if (!internal && !ast->as()) { process_list_entry = context.getProcessList().insert(query, ast.get(), context); context.setProcessListElement(&process_list_entry->get()); @@ -506,7 +506,7 @@ void executeQuery( if (streams.in) { - const auto * ast_query_with_output = ast->As(); + const auto * ast_query_with_output = ast->as(); WriteBuffer * out_buf = &ostr; std::optional out_file_buf; @@ -515,7 +515,7 @@ void executeQuery( if (!allow_into_outfile) throw Exception("INTO OUTFILE is not allowed", ErrorCodes::INTO_OUTFILE_NOT_ALLOWED); - const auto & out_file = ast_query_with_output->out_file->As()->value.safeGet(); + const auto & out_file = ast_query_with_output->out_file->as()->value.safeGet(); out_file_buf.emplace(out_file, DBMS_DEFAULT_BUFFER_SIZE, O_WRONLY | O_EXCL | O_CREAT); out_buf = &*out_file_buf; } diff --git a/dbms/src/Interpreters/getClusterName.cpp b/dbms/src/Interpreters/getClusterName.cpp index b39c041218c..d162cbdab9d 100644 --- a/dbms/src/Interpreters/getClusterName.cpp +++ b/dbms/src/Interpreters/getClusterName.cpp @@ -18,14 +18,14 @@ namespace ErrorCodes std::string getClusterName(const IAST & node) { - if (const auto * ast_id = node.As()) + if (const auto * ast_id = node.as()) return ast_id->name; - if (const auto * ast_lit = node.As()) + if (const auto * ast_lit = node.as()) return ast_lit->value.safeGet(); /// A hack to support hyphens in cluster names. - if (const auto * ast_func = node.As()) + if (const auto * ast_func = node.as()) { if (ast_func->name != "minus" || !ast_func->arguments || ast_func->arguments->children.size() < 2) throw Exception("Illegal expression instead of cluster name.", ErrorCodes::BAD_ARGUMENTS); diff --git a/dbms/src/Interpreters/interpretSubquery.cpp b/dbms/src/Interpreters/interpretSubquery.cpp index bd5443cffeb..d46217695f9 100644 --- a/dbms/src/Interpreters/interpretSubquery.cpp +++ b/dbms/src/Interpreters/interpretSubquery.cpp @@ -19,9 +19,9 @@ std::shared_ptr interpretSubquery( const ASTPtr & table_expression, const Context & context, size_t subquery_depth, const Names & required_source_columns) { /// Subquery or table name. The name of the table is similar to the subquery `SELECT * FROM t`. - const auto * subquery = table_expression->As(); - const auto * function = table_expression->As(); - const auto * table = table_expression->As(); + const auto * subquery = table_expression->as(); + const auto * function = table_expression->as(); + const auto * table = table_expression->as(); if (!subquery && !table && !function) throw Exception("Table expression is undefined, Method: ExpressionAnalyzer::interpretSubquery." , ErrorCodes::LOGICAL_ERROR); @@ -94,9 +94,9 @@ std::shared_ptr interpretSubquery( std::set all_column_names; std::set assigned_column_names; - if (const auto * select_with_union = query->As()) + if (const auto * select_with_union = query->as()) { - if (const auto * select = select_with_union->list_of_selects->children.at(0)->As()) + if (const auto * select = select_with_union->list_of_selects->children.at(0)->as()) { for (auto & expr : select->select_expression_list->children) all_column_names.insert(expr->getAliasOrColumnName()); diff --git a/dbms/src/Interpreters/loadMetadata.cpp b/dbms/src/Interpreters/loadMetadata.cpp index fcec49141d0..334fd5bb490 100644 --- a/dbms/src/Interpreters/loadMetadata.cpp +++ b/dbms/src/Interpreters/loadMetadata.cpp @@ -39,7 +39,7 @@ static void executeCreateQuery( ParserCreateQuery parser; ASTPtr ast = parseQuery(parser, query.data(), query.data() + query.size(), "in file " + file_name, 0); - auto * ast_create_query = ast->As(); + auto * ast_create_query = ast->as(); ast_create_query->attach = true; ast_create_query->database = database; diff --git a/dbms/src/Parsers/ASTAlterQuery.h b/dbms/src/Parsers/ASTAlterQuery.h index d36d9694155..7261170288a 100644 --- a/dbms/src/Parsers/ASTAlterQuery.h +++ b/dbms/src/Parsers/ASTAlterQuery.h @@ -123,7 +123,7 @@ public: void add(const ASTPtr & command) { - commands.push_back(command->As()); + commands.push_back(command->as()); children.push_back(command); } diff --git a/dbms/src/Parsers/ASTFunction.cpp b/dbms/src/Parsers/ASTFunction.cpp index 96d075ec5fe..b45bded9664 100644 --- a/dbms/src/Parsers/ASTFunction.cpp +++ b/dbms/src/Parsers/ASTFunction.cpp @@ -62,7 +62,7 @@ ASTPtr ASTFunction::clone() const */ static bool highlightStringLiteralWithMetacharacters(const ASTPtr & node, const IAST::FormatSettings & settings, const char * metacharacters) { - if (const auto * literal = node->As()) + if (const auto * literal = node->as()) { if (literal->value.getType() == Field::Types::String) { @@ -132,7 +132,7 @@ void ASTFunction::formatImplWithoutAlias(const FormatSettings & settings, Format * Instead, add a space. * PS. You can not just ask to add parentheses - see formatImpl for ASTLiteral. */ - if (name == "negate" && arguments->children[0]->As()) + if (name == "negate" && arguments->children[0]->as()) settings.ostr << ' '; arguments->formatImpl(settings, state, nested_need_parens); @@ -203,7 +203,7 @@ void ASTFunction::formatImplWithoutAlias(const FormatSettings & settings, Format if (!written && 0 == strcmp(name.c_str(), "tupleElement")) { /// It can be printed in a form of 'x.1' only if right hand side is unsigned integer literal. - if (const auto * lit = arguments->children[1]->As()) + if (const auto * lit = arguments->children[1]->as()) { if (lit->value.getType() == Field::Types::UInt64) { @@ -222,7 +222,7 @@ void ASTFunction::formatImplWithoutAlias(const FormatSettings & settings, Format if (frame.need_parens) settings.ostr << '('; - const auto * first_arg_func = arguments->children[0]->As(); + const auto * first_arg_func = arguments->children[0]->as(); if (first_arg_func && first_arg_func->name == "tuple" && first_arg_func->arguments diff --git a/dbms/src/Parsers/ASTIdentifier.cpp b/dbms/src/Parsers/ASTIdentifier.cpp index 19d076d815f..6b0329409a3 100644 --- a/dbms/src/Parsers/ASTIdentifier.cpp +++ b/dbms/src/Parsers/ASTIdentifier.cpp @@ -86,7 +86,7 @@ ASTPtr createTableIdentifier(const String & database_name, const String & table_ std::optional getIdentifierName(const IAST * const ast) { if (ast) - if (const auto * node = ast->As()) + if (const auto * node = ast->as()) return node->name; return {}; } @@ -94,7 +94,7 @@ std::optional getIdentifierName(const IAST * const ast) bool getIdentifierName(const ASTPtr & ast, String & name) { if (ast) - if (const auto * node = ast->As()) + if (const auto * node = ast->as()) { name = node->name; return true; @@ -105,7 +105,7 @@ bool getIdentifierName(const ASTPtr & ast, String & name) void setIdentifierSpecial(ASTPtr & ast) { if (ast) - if (auto * id = ast->As()) + if (auto * id = ast->as()) id->semantic->special = true; } diff --git a/dbms/src/Parsers/ASTQueryWithOutput.cpp b/dbms/src/Parsers/ASTQueryWithOutput.cpp index 22d3c8bcc30..1c67d20be22 100644 --- a/dbms/src/Parsers/ASTQueryWithOutput.cpp +++ b/dbms/src/Parsers/ASTQueryWithOutput.cpp @@ -49,7 +49,7 @@ void ASTQueryWithOutput::formatImpl(const FormatSettings & s, FormatState & stat bool ASTQueryWithOutput::resetOutputASTIfExist(IAST & ast) { - if (auto * ast_with_output = ast.As()) + if (auto * ast_with_output = ast.as()) { ast_with_output->format.reset(); ast_with_output->out_file.reset(); diff --git a/dbms/src/Parsers/ASTRenameQuery.h b/dbms/src/Parsers/ASTRenameQuery.h index 1da34227ee8..b0deb97a145 100644 --- a/dbms/src/Parsers/ASTRenameQuery.h +++ b/dbms/src/Parsers/ASTRenameQuery.h @@ -41,7 +41,7 @@ public: ASTPtr getRewrittenASTWithoutOnCluster(const std::string & new_database) const override { auto query_ptr = clone(); - auto * query = query_ptr->As(); + auto * query = query_ptr->as(); query->cluster.clear(); for (Element & elem : query->elements) diff --git a/dbms/src/Parsers/ASTSelectQuery.cpp b/dbms/src/Parsers/ASTSelectQuery.cpp index dced5f4159a..b3b94335889 100644 --- a/dbms/src/Parsers/ASTSelectQuery.cpp +++ b/dbms/src/Parsers/ASTSelectQuery.cpp @@ -65,7 +65,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << indent_str << "WITH " << (s.hilite ? hilite_none : ""); s.one_line ? with_expression_list->formatImpl(s, state, frame) - : with_expression_list->As()->formatImplMultiline(s, state, frame); + : with_expression_list->as()->formatImplMultiline(s, state, frame); s.ostr << s.nl_or_ws; } @@ -73,7 +73,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.one_line ? select_expression_list->formatImpl(s, state, frame) - : select_expression_list->As()->formatImplMultiline(s, state, frame); + : select_expression_list->as()->formatImplMultiline(s, state, frame); if (tables) { @@ -98,7 +98,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << s.nl_or_ws << indent_str << "GROUP BY " << (s.hilite ? hilite_none : ""); s.one_line ? group_expression_list->formatImpl(s, state, frame) - : group_expression_list->As()->formatImplMultiline(s, state, frame); + : group_expression_list->as()->formatImplMultiline(s, state, frame); } if (group_by_with_rollup) @@ -121,7 +121,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << s.nl_or_ws << indent_str << "ORDER BY " << (s.hilite ? hilite_none : ""); s.one_line ? order_expression_list->formatImpl(s, state, frame) - : order_expression_list->As()->formatImplMultiline(s, state, frame); + : order_expression_list->as()->formatImplMultiline(s, state, frame); } if (limit_by_value) @@ -131,7 +131,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << " BY " << (s.hilite ? hilite_none : ""); s.one_line ? limit_by_expression_list->formatImpl(s, state, frame) - : limit_by_expression_list->As()->formatImplMultiline(s, state, frame); + : limit_by_expression_list->as()->formatImplMultiline(s, state, frame); } if (limit_length) @@ -161,15 +161,15 @@ static const ASTTableExpression * getFirstTableExpression(const ASTSelectQuery & if (!select.tables) return {}; - const auto * tables_in_select_query = select.tables->As(); + const auto * tables_in_select_query = select.tables->as(); if (tables_in_select_query->children.empty()) return {}; - const auto * tables_element = tables_in_select_query->children[0]->As(); + const auto * tables_element = tables_in_select_query->children[0]->as(); if (!tables_element->table_expression) return {}; - return tables_element->table_expression->As(); + return tables_element->table_expression->as(); } static ASTTableExpression * getFirstTableExpression(ASTSelectQuery & select) @@ -177,15 +177,15 @@ static ASTTableExpression * getFirstTableExpression(ASTSelectQuery & select) if (!select.tables) return {}; - auto * tables_in_select_query = select.tables->As(); + auto * tables_in_select_query = select.tables->as(); if (tables_in_select_query->children.empty()) return {}; - auto * tables_element = tables_in_select_query->children[0]->As(); + auto * tables_element = tables_in_select_query->children[0]->as(); if (!tables_element->table_expression) return {}; - return tables_element->table_expression->As(); + return tables_element->table_expression->as(); } static const ASTArrayJoin * getFirstArrayJoin(const ASTSelectQuery & select) @@ -193,18 +193,18 @@ static const ASTArrayJoin * getFirstArrayJoin(const ASTSelectQuery & select) if (!select.tables) return {}; - const auto * tables_in_select_query = select.tables->As(); + const auto * tables_in_select_query = select.tables->as(); if (tables_in_select_query->children.empty()) return {}; const ASTArrayJoin * array_join = nullptr; for (const auto & child : tables_in_select_query->children) { - const auto * tables_element = child->As(); + const auto * tables_element = child->as(); if (tables_element->array_join) { if (!array_join) - array_join = tables_element->array_join->As(); + array_join = tables_element->array_join->as(); else throw Exception("Support for more than one ARRAY JOIN in query is not implemented", ErrorCodes::NOT_IMPLEMENTED); } @@ -218,14 +218,14 @@ static const ASTTablesInSelectQueryElement * getFirstTableJoin(const ASTSelectQu if (!select.tables) return {}; - const auto * tables_in_select_query = select.tables->As(); + const auto * tables_in_select_query = select.tables->as(); if (tables_in_select_query->children.empty()) return {}; const ASTTablesInSelectQueryElement * joined_table = nullptr; for (const auto & child : tables_in_select_query->children) { - const auto * tables_element = child->As(); + const auto * tables_element = child->as(); if (tables_element->table_join) { if (!joined_table) diff --git a/dbms/src/Parsers/ASTTablesInSelectQuery.cpp b/dbms/src/Parsers/ASTTablesInSelectQuery.cpp index 3947200f705..da8ae0a4a2d 100644 --- a/dbms/src/Parsers/ASTTablesInSelectQuery.cpp +++ b/dbms/src/Parsers/ASTTablesInSelectQuery.cpp @@ -208,7 +208,7 @@ void ASTArrayJoin::formatImpl(const FormatSettings & settings, FormatState & sta settings.one_line ? expression_list->formatImpl(settings, state, frame) - : expression_list->As()->formatImplMultiline(settings, state, frame); + : expression_list->as()->formatImplMultiline(settings, state, frame); } @@ -218,7 +218,7 @@ void ASTTablesInSelectQueryElement::formatImpl(const FormatSettings & settings, { if (table_join) { - table_join->As()->formatImplBeforeTable(settings, state, frame); + table_join->as()->formatImplBeforeTable(settings, state, frame); settings.ostr << " "; } @@ -226,7 +226,7 @@ void ASTTablesInSelectQueryElement::formatImpl(const FormatSettings & settings, settings.ostr << " "; if (table_join) - table_join->As()->formatImplAfterTable(settings, state, frame); + table_join->as()->formatImplAfterTable(settings, state, frame); } else if (array_join) { diff --git a/dbms/src/Parsers/ExpressionElementParsers.cpp b/dbms/src/Parsers/ExpressionElementParsers.cpp index 4a1c7393d99..4f19469c756 100644 --- a/dbms/src/Parsers/ExpressionElementParsers.cpp +++ b/dbms/src/Parsers/ExpressionElementParsers.cpp @@ -82,7 +82,7 @@ bool ParserParenthesisExpression::parseImpl(Pos & pos, ASTPtr & node, Expected & return false; ++pos; - const auto * expr_list = contents_node->As(); + const auto * expr_list = contents_node->as(); /// empty expression in parentheses is not allowed if (expr_list->children.empty()) @@ -170,7 +170,7 @@ bool ParserCompoundIdentifier::parseImpl(Pos & pos, ASTPtr & node, Expected & ex String name; std::vector parts; - const auto * list = id_list->As(); + const auto * list = id_list->as(); for (const auto & child : list->children) { if (!name.empty()) @@ -1075,7 +1075,7 @@ bool ParserArrayOfLiterals::parseImpl(Pos & pos, ASTPtr & node, Expected & expec if (!literal_p.parse(pos, literal_node, expected)) return false; - arr.push_back(literal_node->As()->value); + arr.push_back(literal_node->as()->value); } expected.add(pos, "closing square bracket"); @@ -1254,7 +1254,7 @@ bool ParserWithOptionalAlias::parseImpl(Pos & pos, ASTPtr & node, Expected & exp ASTPtr alias_node; if (ParserAlias(allow_alias_without_as_keyword_now).parse(pos, alias_node, expected)) { - if (auto * ast_with_alias = node->As()) + if (auto * ast_with_alias = node->as()) { getIdentifierName(alias_node, ast_with_alias->alias); ast_with_alias->prefer_alias_to_column_name = prefer_alias_to_column_name; diff --git a/dbms/src/Parsers/ExpressionListParsers.cpp b/dbms/src/Parsers/ExpressionListParsers.cpp index ba59a01ddeb..9fc72c4520e 100644 --- a/dbms/src/Parsers/ExpressionListParsers.cpp +++ b/dbms/src/Parsers/ExpressionListParsers.cpp @@ -213,7 +213,7 @@ bool ParserVariableArityOperatorList::parseImpl(Pos & pos, ASTPtr & node, Expect if (!arguments) { node = makeASTFunction(function_name, node); - arguments = node->As()->arguments; + arguments = node->as()->arguments; } ASTPtr elem; diff --git a/dbms/src/Parsers/IAST.h b/dbms/src/Parsers/IAST.h index 3d9a738a9f2..294d7453c41 100644 --- a/dbms/src/Parsers/IAST.h +++ b/dbms/src/Parsers/IAST.h @@ -43,13 +43,13 @@ public: IAST & operator=(const IAST &) = default; template - Derived * As() + Derived * as() { return typeid_cast(this); } template - const Derived * As() const + const Derived * as() const { return typeid_cast(this); } diff --git a/dbms/src/Parsers/IAST_fwd.h b/dbms/src/Parsers/IAST_fwd.h index f5ceb8d2e41..30408a3792f 100644 --- a/dbms/src/Parsers/IAST_fwd.h +++ b/dbms/src/Parsers/IAST_fwd.h @@ -3,7 +3,8 @@ #include #include -namespace DB { +namespace DB +{ class IAST; using ASTPtr = std::shared_ptr; diff --git a/dbms/src/Parsers/ParserAlterQuery.cpp b/dbms/src/Parsers/ParserAlterQuery.cpp index 1d58a49937c..70d84fea111 100644 --- a/dbms/src/Parsers/ParserAlterQuery.cpp +++ b/dbms/src/Parsers/ParserAlterQuery.cpp @@ -202,7 +202,7 @@ bool ParserAlterCommand::parseImpl(Pos & pos, ASTPtr & node, Expected & expected if (!parser_string_literal.parse(pos, ast_from, expected)) return false; - command->from = ast_from->As()->value.get(); + command->from = ast_from->as()->value.get(); command->type = ASTAlterCommand::FETCH_PARTITION; } else if (s_freeze.ignore(pos, expected)) @@ -229,7 +229,7 @@ bool ParserAlterCommand::parseImpl(Pos & pos, ASTPtr & node, Expected & expected if (!parser_string_literal.parse(pos, ast_with_name, expected)) return false; - command->with_name = ast_with_name->As()->value.get(); + command->with_name = ast_with_name->as()->value.get(); } } else if (s_modify_column.ignore(pos, expected)) diff --git a/dbms/src/Parsers/ParserCreateQuery.cpp b/dbms/src/Parsers/ParserCreateQuery.cpp index fb28c3bb956..eaa68351095 100644 --- a/dbms/src/Parsers/ParserCreateQuery.cpp +++ b/dbms/src/Parsers/ParserCreateQuery.cpp @@ -126,8 +126,8 @@ bool ParserIndexDeclaration::parseImpl(Pos & pos, ASTPtr & node, Expected & expe return false; auto index = std::make_shared(); - index->name = name->As()->name; - index->granularity = granularity->As()->value.get(); + index->name = name->as()->name; + index->granularity = granularity->as()->value.get(); index->set(index->expr, expr); index->set(index->type, type); node = index; @@ -179,9 +179,9 @@ bool ParserColumnsOrIndicesDeclarationList::parseImpl(Pos & pos, ASTPtr & node, for (const auto & elem : list->children) { - if (elem->As()) + if (elem->as()) columns->children.push_back(elem); - else if (elem->As()) + else if (elem->as()) indices->children.push_back(elem); else return false; diff --git a/dbms/src/Parsers/ParserDropQuery.cpp b/dbms/src/Parsers/ParserDropQuery.cpp index 21b034dbbec..ca757ae6168 100644 --- a/dbms/src/Parsers/ParserDropQuery.cpp +++ b/dbms/src/Parsers/ParserDropQuery.cpp @@ -34,7 +34,7 @@ bool ParserDropQuery::parseDetachQuery(Pos & pos, ASTPtr & node, Expected & expe { if (parseDropQuery(pos, node, expected)) { - auto * drop_query = node->As(); + auto * drop_query = node->as(); drop_query->kind = ASTDropQuery::Kind::Detach; return true; } @@ -45,7 +45,7 @@ bool ParserDropQuery::parseTruncateQuery(Pos & pos, ASTPtr & node, Expected & ex { if (parseDropQuery(pos, node, expected)) { - auto * drop_query = node->As(); + auto * drop_query = node->as(); drop_query->kind = ASTDropQuery::Kind::Truncate; return true; } diff --git a/dbms/src/Parsers/ParserPartition.cpp b/dbms/src/Parsers/ParserPartition.cpp index abb972a1aa7..d2405cb81c8 100644 --- a/dbms/src/Parsers/ParserPartition.cpp +++ b/dbms/src/Parsers/ParserPartition.cpp @@ -26,7 +26,7 @@ bool ParserPartition::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) if (!parser_string_literal.parse(pos, partition_id, expected)) return false; - partition->id = partition_id->As()->value.get(); + partition->id = partition_id->as()->value.get(); } else { @@ -37,10 +37,10 @@ bool ParserPartition::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) size_t fields_count; StringRef fields_str; - const auto * tuple_ast = value->As(); + const auto * tuple_ast = value->as(); if (tuple_ast && tuple_ast->name == "tuple") { - const auto * arguments_ast = tuple_ast->arguments->As(); + const auto * arguments_ast = tuple_ast->arguments->as(); if (arguments_ast) fields_count = arguments_ast->children.size(); else diff --git a/dbms/src/Parsers/ParserQueryWithOutput.cpp b/dbms/src/Parsers/ParserQueryWithOutput.cpp index 35c78bb91e6..1b38cee3ba5 100644 --- a/dbms/src/Parsers/ParserQueryWithOutput.cpp +++ b/dbms/src/Parsers/ParserQueryWithOutput.cpp @@ -62,7 +62,7 @@ bool ParserQueryWithOutput::parseImpl(Pos & pos, ASTPtr & node, Expected & expec if (!parsed) return false; - auto * query_with_output = query->As(); + auto * query_with_output = query->as(); ParserKeyword s_into_outfile("INTO OUTFILE"); if (s_into_outfile.ignore(pos, expected)) diff --git a/dbms/src/Parsers/ParserSelectWithUnionQuery.cpp b/dbms/src/Parsers/ParserSelectWithUnionQuery.cpp index ff2f13342ef..cebe8ba876d 100644 --- a/dbms/src/Parsers/ParserSelectWithUnionQuery.cpp +++ b/dbms/src/Parsers/ParserSelectWithUnionQuery.cpp @@ -11,7 +11,7 @@ namespace DB static void getSelectsFromUnionListNode(ASTPtr & ast_select, ASTs & selects) { - if (auto * inner_union = ast_select->As()) + if (auto * inner_union = ast_select->as()) { for (auto & child : inner_union->list_of_selects->children) getSelectsFromUnionListNode(child, selects); diff --git a/dbms/src/Parsers/ParserSetQuery.cpp b/dbms/src/Parsers/ParserSetQuery.cpp index d925890d5e9..25ca6877246 100644 --- a/dbms/src/Parsers/ParserSetQuery.cpp +++ b/dbms/src/Parsers/ParserSetQuery.cpp @@ -32,7 +32,7 @@ static bool parseNameValuePair(ASTSetQuery::Change & change, IParser::Pos & pos, return false; getIdentifierName(name, change.name); - change.value = value->As()->value; + change.value = value->as()->value; return true; } diff --git a/dbms/src/Parsers/ParserShowTablesQuery.cpp b/dbms/src/Parsers/ParserShowTablesQuery.cpp index 4a95ca3b1ee..1fb9ea9bab7 100644 --- a/dbms/src/Parsers/ParserShowTablesQuery.cpp +++ b/dbms/src/Parsers/ParserShowTablesQuery.cpp @@ -67,7 +67,7 @@ bool ParserShowTablesQuery::parseImpl(Pos & pos, ASTPtr & node, Expected & expec getIdentifierName(database, query->from); if (like) - query->like = safeGet(like->As()->value); + query->like = safeGet(like->as()->value); node = query; diff --git a/dbms/src/Parsers/ParserUnionQueryElement.cpp b/dbms/src/Parsers/ParserUnionQueryElement.cpp index 1e1e1908384..efd022e6362 100644 --- a/dbms/src/Parsers/ParserUnionQueryElement.cpp +++ b/dbms/src/Parsers/ParserUnionQueryElement.cpp @@ -13,7 +13,7 @@ bool ParserUnionQueryElement::parseImpl(Pos & pos, ASTPtr & node, Expected & exp if (!ParserSubquery().parse(pos, node, expected) && !ParserSelectQuery().parse(pos, node, expected)) return false; - if (const auto * ast_subquery = node->As()) + if (const auto * ast_subquery = node->as()) node = ast_subquery->children.at(0); return true; diff --git a/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp b/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp index 3eefeb049d3..70936dfe0e0 100644 --- a/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp +++ b/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp @@ -17,7 +17,7 @@ bool parseIdentifierOrStringLiteral(IParser::Pos & pos, Expected & expected, Str if (!ParserStringLiteral().parse(pos, res, expected)) return false; - result = res->As()->value.safeGet(); + result = res->as()->value.safeGet(); } else result = *getIdentifierName(res); diff --git a/dbms/src/Parsers/parseQuery.cpp b/dbms/src/Parsers/parseQuery.cpp index 5eb128ae6ec..3d761d09b13 100644 --- a/dbms/src/Parsers/parseQuery.cpp +++ b/dbms/src/Parsers/parseQuery.cpp @@ -236,7 +236,7 @@ ASTPtr tryParseQuery( /// If parsed query ends at data for insertion. Data for insertion could be in any format and not necessary be lexical correct. ASTInsertQuery * insert = nullptr; if (parse_res) - insert = res->As(); + insert = res->as(); if (!(insert && insert->data)) { @@ -355,7 +355,7 @@ std::pair splitMultipartQuery(const std::string & queries, s ast = parseQueryAndMovePosition(parser, pos, end, "", true, 0); - auto * insert = ast->As(); + auto * insert = ast->as(); if (insert && insert->data) { diff --git a/dbms/src/Storages/AlterCommands.cpp b/dbms/src/Storages/AlterCommands.cpp index e36b97af712..048373969ff 100644 --- a/dbms/src/Storages/AlterCommands.cpp +++ b/dbms/src/Storages/AlterCommands.cpp @@ -39,7 +39,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = AlterCommand::ADD_COLUMN; - const auto * ast_col_decl = command_ast->col_decl->As(); + const auto * ast_col_decl = command_ast->col_decl->as(); command.column_name = ast_col_decl->name; if (ast_col_decl->type) @@ -78,7 +78,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = AlterCommand::MODIFY_COLUMN; - const auto * ast_col_decl = command_ast->col_decl->As(); + const auto * ast_col_decl = command_ast->col_decl->as(); command.column_name = ast_col_decl->name; if (ast_col_decl->type) @@ -97,7 +97,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ if (ast_col_decl->comment) { - const auto * ast_comment = ast_col_decl->comment->As(); + const auto * ast_comment = ast_col_decl->comment->as(); command.comment = ast_comment->value.get(); } command.if_exists = command_ast->if_exists; @@ -109,7 +109,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = COMMENT_COLUMN; command.column_name = *getIdentifierName(command_ast->column); - const auto * ast_comment = command_ast->comment->As(); + const auto * ast_comment = command_ast->comment->as(); command.comment = ast_comment->value.get(); command.if_exists = command_ast->if_exists; return command; @@ -127,12 +127,12 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.index_decl = command_ast->index_decl; command.type = AlterCommand::ADD_INDEX; - const auto * ast_index_decl = command_ast->index_decl->As(); + const auto * ast_index_decl = command_ast->index_decl->as(); command.index_name = ast_index_decl->name; if (command_ast->index) - command.after_index_name = command_ast->index->As()->name; + command.after_index_name = command_ast->index->as()->name; command.if_not_exists = command_ast->if_not_exists; @@ -145,7 +145,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = AlterCommand::DROP_INDEX; - command.index_name = command_ast->index->As()->name; + command.index_name = command_ast->index->as()->name; command.if_exists = command_ast->if_exists; return command; @@ -335,7 +335,7 @@ void AlterCommand::apply(ColumnsDescription & columns_description, IndicesDescri indices_description.indices.cend(), [this](const ASTPtr & index_ast) { - return index_ast->As()->name == index_name; + return index_ast->as()->name == index_name; })) { if (if_not_exists) @@ -354,7 +354,7 @@ void AlterCommand::apply(ColumnsDescription & columns_description, IndicesDescri indices_description.indices.end(), [this](const ASTPtr & index_ast) { - return index_ast->As()->name == after_index_name; + return index_ast->as()->name == after_index_name; }); if (insert_it == indices_description.indices.end()) @@ -373,7 +373,7 @@ void AlterCommand::apply(ColumnsDescription & columns_description, IndicesDescri indices_description.indices.end(), [this](const ASTPtr & index_ast) { - return index_ast->As()->name == index_name; + return index_ast->as()->name == index_name; }); if (erase_it == indices_description.indices.end()) diff --git a/dbms/src/Storages/ColumnsDescription.cpp b/dbms/src/Storages/ColumnsDescription.cpp index d4baa0ed635..0a7e8f4abc5 100644 --- a/dbms/src/Storages/ColumnsDescription.cpp +++ b/dbms/src/Storages/ColumnsDescription.cpp @@ -158,7 +158,7 @@ void parseColumn(ReadBufferFromString & buf, ColumnsDescription & result, const String column_line; readEscapedStringUntilEOL(column_line, buf); ASTPtr ast = parseQuery(column_parser, column_line, "column parser", 0); - if (const auto * col_ast = ast->As()) + if (const auto * col_ast = ast->as()) { String column_name = col_ast->name; auto type = data_type_factory.get(col_ast->type); @@ -185,7 +185,7 @@ void parseColumn(ReadBufferFromString & buf, ColumnsDescription & result, const result.ordinary.emplace_back(column_name, std::move(type)); if (col_ast->comment) - if (auto comment_str = col_ast->comment->As()->value.get(); !comment_str.empty()) + if (auto comment_str = col_ast->comment->as()->value.get(); !comment_str.empty()) result.comments.emplace(column_name, std::move(comment_str)); if (col_ast->codec) diff --git a/dbms/src/Storages/Kafka/StorageKafka.cpp b/dbms/src/Storages/Kafka/StorageKafka.cpp index 80aae9ebe18..a5917d1fd98 100644 --- a/dbms/src/Storages/Kafka/StorageKafka.cpp +++ b/dbms/src/Storages/Kafka/StorageKafka.cpp @@ -409,7 +409,7 @@ void registerStorageKafka(StorageFactory & factory) String brokers; if (args_count >= 1) { - const auto * ast = engine_args[0]->As(); + const auto * ast = engine_args[0]->as(); if (ast && ast->value.getType() == Field::Types::String) { brokers = safeGet(ast->value); @@ -429,7 +429,7 @@ void registerStorageKafka(StorageFactory & factory) if (args_count >= 2) { engine_args[1] = evaluateConstantExpressionAsLiteral(engine_args[1], args.local_context); - topic_list = engine_args[1]->As()->value.safeGet(); + topic_list = engine_args[1]->as()->value.safeGet(); } else if (kafka_settings.kafka_topic_list.changed) { @@ -447,7 +447,7 @@ void registerStorageKafka(StorageFactory & factory) if (args_count >= 3) { engine_args[2] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[2], args.local_context); - group = engine_args[2]->As()->value.safeGet(); + group = engine_args[2]->as()->value.safeGet(); } else if (kafka_settings.kafka_group_name.changed) { @@ -460,7 +460,7 @@ void registerStorageKafka(StorageFactory & factory) { engine_args[3] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[3], args.local_context); - const auto * ast = engine_args[3]->As(); + const auto * ast = engine_args[3]->as(); if (ast && ast->value.getType() == Field::Types::String) { format = safeGet(ast->value); @@ -481,7 +481,7 @@ void registerStorageKafka(StorageFactory & factory) { engine_args[4] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[4], args.local_context); - const auto * ast = engine_args[4]->As(); + const auto * ast = engine_args[4]->as(); String arg; if (ast && ast->value.getType() == Field::Types::String) { @@ -515,7 +515,7 @@ void registerStorageKafka(StorageFactory & factory) { engine_args[5] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[5], args.local_context); - const auto * ast = engine_args[5]->As(); + const auto * ast = engine_args[5]->as(); if (ast && ast->value.getType() == Field::Types::String) { schema = safeGet(ast->value); @@ -534,7 +534,7 @@ void registerStorageKafka(StorageFactory & factory) UInt64 num_consumers = 1; if (args_count >= 7) { - const auto * ast = engine_args[6]->As(); + const auto * ast = engine_args[6]->as(); if (ast && ast->value.getType() == Field::Types::UInt64) { num_consumers = safeGet(ast->value); @@ -553,7 +553,7 @@ void registerStorageKafka(StorageFactory & factory) UInt64 max_block_size = 0; if (args_count >= 8) { - const auto * ast = engine_args[7]->As(); + const auto * ast = engine_args[7]->as(); if (ast && ast->value.getType() == Field::Types::UInt64) { max_block_size = static_cast(safeGet(ast->value)); @@ -572,7 +572,7 @@ void registerStorageKafka(StorageFactory & factory) size_t skip_broken = 0; if (args_count >= 9) { - const auto * ast = engine_args[8]->As(); + const auto * ast = engine_args[8]->as(); if (ast && ast->value.getType() == Field::Types::UInt64) { skip_broken = static_cast(safeGet(ast->value)); diff --git a/dbms/src/Storages/MergeTree/KeyCondition.cpp b/dbms/src/Storages/MergeTree/KeyCondition.cpp index e75228d4cb0..c30d8da6fb1 100644 --- a/dbms/src/Storages/MergeTree/KeyCondition.cpp +++ b/dbms/src/Storages/MergeTree/KeyCondition.cpp @@ -284,7 +284,7 @@ KeyCondition::KeyCondition( Block block_with_constants = getBlockWithConstants(query_info.query, query_info.syntax_analyzer_result, context); /// Trasform WHERE section to Reverse Polish notation - const auto * select = query_info.query->As(); + const auto * select = query_info.query->as(); if (select->where_expression) { traverseAST(select->where_expression, context, block_with_constants); @@ -321,7 +321,7 @@ static bool getConstant(const ASTPtr & expr, Block & block_with_constants, Field { String column_name = expr->getColumnName(); - if (const auto * lit = expr->As()) + if (const auto * lit = expr->as()) { /// By default block_with_constants has only one column named "_dummy". /// If block contains only constants it's may not be preprocessed by @@ -370,7 +370,7 @@ void KeyCondition::traverseAST(const ASTPtr & node, const Context & context, Blo { RPNElement element; - if (auto * func = node->As()) + if (auto * func = node->as()) { if (operatorFromAST(func, element)) { @@ -486,7 +486,7 @@ bool KeyCondition::tryPrepareSetIndex( } }; - const auto * left_arg_tuple = left_arg->As(); + const auto * left_arg_tuple = left_arg->as(); if (left_arg_tuple && left_arg_tuple->name == "tuple") { const auto & tuple_elements = left_arg_tuple->arguments->children; @@ -502,7 +502,7 @@ bool KeyCondition::tryPrepareSetIndex( const ASTPtr & right_arg = args[1]; PreparedSetKey set_key; - if (right_arg->As() || right_arg->As()) + if (right_arg->as() || right_arg->as()) set_key = PreparedSetKey::forSubquery(*right_arg); else set_key = PreparedSetKey::forLiteral(*right_arg, data_types); @@ -574,7 +574,7 @@ bool KeyCondition::isKeyPossiblyWrappedByMonotonicFunctionsImpl( return true; } - if (const auto * func = node->As()) + if (const auto * func = node->as()) { const auto & args = func->arguments->children; if (args.size() != 1) @@ -620,9 +620,9 @@ bool KeyCondition::atomFromAST(const ASTPtr & node, const Context & context, Blo */ Field const_value; DataTypePtr const_type; - if (const auto * func = node->As()) + if (const auto * func = node->as()) { - const ASTs & args = func->arguments->As()->children; + const ASTs & args = func->arguments->as()->children; if (args.size() != 2) return false; diff --git a/dbms/src/Storages/MergeTree/MergeTreeData.cpp b/dbms/src/Storages/MergeTree/MergeTreeData.cpp index 293b41ead0a..e671870b133 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeData.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeData.cpp @@ -405,7 +405,7 @@ ASTPtr MergeTreeData::extractKeyExpressionList(const ASTPtr & node) if (!node) return std::make_shared(); - const auto * expr_func = node->As(); + const auto * expr_func = node->as(); if (expr_func && expr_func->name == "tuple") { @@ -1174,10 +1174,10 @@ void MergeTreeData::createConvertExpression(const DataPartPtr & part, const Name /// Remove old indices std::set new_indices_set; for (const auto & index_decl : new_indices) - new_indices_set.emplace(index_decl->As()->name); + new_indices_set.emplace(index_decl->as()->name); for (const auto & index_decl : old_indices) { - const auto * index = index_decl->As(); + const auto * index = index_decl->as(); if (!new_indices_set.count(index->name)) { out_rename_map["skp_idx_" + index->name + ".idx"] = ""; @@ -2220,7 +2220,7 @@ void MergeTreeData::freezePartition(const ASTPtr & partition_ast, const String & if (format_version < MERGE_TREE_DATA_MIN_FORMAT_VERSION_WITH_CUSTOM_PARTITIONING) { /// Month-partitioning specific - partition value can represent a prefix of the partition to freeze. - if (const auto * partition_lit = partition_ast->As()->value->As()) + if (const auto * partition_lit = partition_ast->as()->value->as()) prefix = partition_lit->value.getType() == Field::Types::UInt64 ? toString(partition_lit->value.get()) : partition_lit->value.safeGet(); @@ -2275,7 +2275,7 @@ size_t MergeTreeData::getPartitionSize(const std::string & partition_id) const String MergeTreeData::getPartitionIDFromQuery(const ASTPtr & ast, const Context & context) { - const auto * partition_ast = ast->As(); + const auto * partition_ast = ast->as(); if (!partition_ast->value) return partition_ast->id; @@ -2283,7 +2283,7 @@ String MergeTreeData::getPartitionIDFromQuery(const ASTPtr & ast, const Context if (format_version < MERGE_TREE_DATA_MIN_FORMAT_VERSION_WITH_CUSTOM_PARTITIONING) { /// Month-partitioning specific - partition ID can be passed in the partition value. - const auto * partition_lit = partition_ast->value->As(); + const auto * partition_lit = partition_ast->value->as(); if (partition_lit && partition_lit->value.getType() == Field::Types::String) { String partition_id = partition_lit->value.get(); @@ -2501,7 +2501,7 @@ bool MergeTreeData::isPrimaryOrMinMaxKeyColumnPossiblyWrappedInFunctions(const A if (column_name == name) return true; - if (const auto * func = node->As()) + if (const auto * func = node->as()) if (func->arguments->children.size() == 1) return isPrimaryOrMinMaxKeyColumnPossiblyWrappedInFunctions(func->arguments->children.front()); @@ -2513,7 +2513,7 @@ bool MergeTreeData::mayBenefitFromIndexForIn(const ASTPtr & left_in_operand) con /// Make sure that the left side of the IN operator contain part of the key. /// If there is a tuple on the left side of the IN operator, at least one item of the tuple /// must be part of the key (probably wrapped by a chain of some acceptable functions). - const auto * left_in_operand_tuple = left_in_operand->As(); + const auto * left_in_operand_tuple = left_in_operand->as(); if (left_in_operand_tuple && left_in_operand_tuple->name == "tuple") { for (const auto & item : left_in_operand_tuple->arguments->children) diff --git a/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp b/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp index 6ead1f3a348..67df82e83e1 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp @@ -129,7 +129,7 @@ static RelativeSize convertAbsoluteSampleSizeToRelative(const ASTPtr & node, siz if (approx_total_rows == 0) return 1; - const auto * node_sample = node->As(); + const auto * node_sample = node->as(); auto absolute_sample_size = node_sample->ratio.numerator / node_sample->ratio.denominator; return std::min(RelativeSize(1), RelativeSize(absolute_sample_size) / RelativeSize(approx_total_rows)); @@ -287,7 +287,7 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( RelativeSize relative_sample_size = 0; RelativeSize relative_sample_offset = 0; - const auto * select = query_info.query->As(); + const auto * select = query_info.query->as(); auto select_sample_size = select->sample_size(); auto select_sample_offset = select->sample_offset(); @@ -295,8 +295,8 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( if (select_sample_size) { relative_sample_size.assign( - select_sample_size->As()->ratio.numerator, - select_sample_size->As()->ratio.denominator); + select_sample_size->as()->ratio.numerator, + select_sample_size->as()->ratio.denominator); if (relative_sample_size < 0) throw Exception("Negative sample size", ErrorCodes::ARGUMENT_OUT_OF_BOUND); @@ -304,8 +304,8 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( relative_sample_offset = 0; if (select_sample_offset) relative_sample_offset.assign( - select_sample_offset->As()->ratio.numerator, - select_sample_offset->As()->ratio.denominator); + select_sample_offset->as()->ratio.numerator, + select_sample_offset->as()->ratio.denominator); if (relative_sample_offset < 0) throw Exception("Negative sample offset", ErrorCodes::ARGUMENT_OUT_OF_BOUND); diff --git a/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp b/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp index ff7de6d2458..089dc3ed8f3 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp @@ -225,7 +225,7 @@ SetIndexCondition::SetIndexCondition( key_columns.insert(name); } - const auto * select = query.query->As(); + const auto * select = query.query->as(); /// Replace logical functions with bit functions. /// Working with UInt8: last bit = can be true, previous = can be false. @@ -298,7 +298,7 @@ void SetIndexCondition::traverseAST(ASTPtr & node) const { if (operatorFromAST(node)) { - auto & args = node->As()->arguments->children; + auto & args = node->as()->arguments->children; for (auto & arg : args) traverseAST(arg); @@ -313,13 +313,13 @@ bool SetIndexCondition::atomFromAST(ASTPtr & node) const { /// Function, literal or column - if (node->As()) + if (node->as()) return true; - if (const auto * identifier = node->As()) + if (const auto * identifier = node->as()) return key_columns.count(identifier->getColumnName()) != 0; - if (auto * func = node->As()) + if (auto * func = node->as()) { if (key_columns.count(func->getColumnName())) { @@ -343,7 +343,7 @@ bool SetIndexCondition::atomFromAST(ASTPtr & node) const bool SetIndexCondition::operatorFromAST(ASTPtr & node) const { /// Functions AND, OR, NOT. Replace with bit*. - auto * func = node->As(); + auto * func = node->as(); if (!func) return false; @@ -418,7 +418,7 @@ static bool checkAtomName(const String & name) bool SetIndexCondition::checkASTUseless(const ASTPtr &node, bool atomic) const { - if (const auto * func = node->As()) + if (const auto * func = node->as()) { if (key_columns.count(func->getColumnName())) return false; @@ -437,9 +437,9 @@ bool SetIndexCondition::checkASTUseless(const ASTPtr &node, bool atomic) const return std::any_of(args.begin(), args.end(), [this, &atomic](const auto & arg) { return checkASTUseless(arg, atomic); }); } - else if (const auto * literal = node->As()) + else if (const auto * literal = node->as()) return !atomic && literal->value.get(); - else if (const auto * identifier = node->As()) + else if (const auto * identifier = node->as()) return key_columns.find(identifier->getColumnName()) == key_columns.end(); else return true; @@ -475,7 +475,7 @@ std::unique_ptr setIndexCreator( if (!node->type->arguments || node->type->arguments->children.size() != 1) throw Exception("Set index must have exactly one argument.", ErrorCodes::INCORRECT_QUERY); else if (node->type->arguments->children.size() == 1) - max_rows = node->type->arguments->children[0]->As()->value.get(); + max_rows = node->type->arguments->children[0]->as()->value.get(); ASTPtr expr_list = MergeTreeData::extractKeyExpressionList(node->expr->clone()); diff --git a/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp b/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp index 3bd77b33af4..ac43508ae42 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp @@ -44,8 +44,8 @@ MergeTreeWhereOptimizer::MergeTreeWhereOptimizer( first_primary_key_column = data.primary_key_columns[0]; calculateColumnSizes(data, queried_columns); - determineArrayJoinedNames(*query_info.query->As()); - optimize(*query_info.query->As()); + determineArrayJoinedNames(*query_info.query->as()); + optimize(*query_info.query->as()); } @@ -65,7 +65,7 @@ static void collectIdentifiersNoSubqueries(const ASTPtr & ast, NameSet & set) if (auto opt_name = getIdentifierName(ast)) return (void)set.insert(*opt_name); - if (ast->As()) + if (ast->as()) return; for (const auto & child : ast->children) @@ -74,7 +74,7 @@ static void collectIdentifiersNoSubqueries(const ASTPtr & ast, NameSet & set) void MergeTreeWhereOptimizer::analyzeImpl(Conditions & res, const ASTPtr & node) const { - if (const auto * func_and = node->As(); func_and && func_and->name == "and") + if (const auto * func_and = node->as(); func_and && func_and->name == "and") { for (const auto & elem : func_and->arguments->children) analyzeImpl(res, elem); @@ -218,7 +218,7 @@ UInt64 MergeTreeWhereOptimizer::getIdentifiersColumnSize(const NameSet & identif bool MergeTreeWhereOptimizer::isConditionGood(const ASTPtr & condition) const { - const auto * function = condition->As(); + const auto * function = condition->as(); if (!function) return false; @@ -231,13 +231,13 @@ bool MergeTreeWhereOptimizer::isConditionGood(const ASTPtr & condition) const auto right_arg = function->arguments->children.back().get(); /// try to ensure left_arg points to ASTIdentifier - if (!left_arg->As() && right_arg->As()) + if (!left_arg->as() && right_arg->as()) std::swap(left_arg, right_arg); - if (left_arg->As()) + if (left_arg->as()) { /// condition may be "good" if only right_arg is a constant and its value is outside the threshold - if (const auto * literal = right_arg->As()) + if (const auto * literal = right_arg->as()) { const auto & field = literal->value; const auto type = field.getType(); @@ -267,7 +267,7 @@ bool MergeTreeWhereOptimizer::isConditionGood(const ASTPtr & condition) const bool MergeTreeWhereOptimizer::hasPrimaryKeyAtoms(const ASTPtr & ast) const { - if (const auto * func = ast->As()) + if (const auto * func = ast->as()) { const auto & args = func->arguments->children; @@ -287,7 +287,7 @@ bool MergeTreeWhereOptimizer::hasPrimaryKeyAtoms(const ASTPtr & ast) const bool MergeTreeWhereOptimizer::isPrimaryKeyAtom(const ASTPtr & ast) const { - if (const auto * func = ast->As()) + if (const auto * func = ast->as()) { if (!KeyCondition::atom_map.count(func->name)) return false; @@ -313,7 +313,7 @@ bool MergeTreeWhereOptimizer::isConstant(const ASTPtr & expr) const { const auto column_name = expr->getColumnName(); - if (expr->As() + if (expr->as() || (block_with_constants.has(column_name) && block_with_constants.getByName(column_name).column->isColumnConst())) return true; @@ -333,7 +333,7 @@ bool MergeTreeWhereOptimizer::isSubsetOfTableColumns(const NameSet & identifiers bool MergeTreeWhereOptimizer::cannotBeMoved(const ASTPtr & ptr) const { - if (const auto * function_ptr = ptr->As()) + if (const auto * function_ptr = ptr->as()) { /// disallow arrayJoin expressions to be moved to PREWHERE for now if ("arrayJoin" == function_ptr->name) diff --git a/dbms/src/Storages/MergeTree/registerStorageMergeTree.cpp b/dbms/src/Storages/MergeTree/registerStorageMergeTree.cpp index 398fcc48fd0..b08300bb039 100644 --- a/dbms/src/Storages/MergeTree/registerStorageMergeTree.cpp +++ b/dbms/src/Storages/MergeTree/registerStorageMergeTree.cpp @@ -37,7 +37,7 @@ namespace ErrorCodes */ static Names extractColumnNames(const ASTPtr & node) { - const auto * expr_func = node->As(); + const auto * expr_func = node->as(); if (expr_func && expr_func->name == "tuple") { @@ -476,7 +476,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) if (replicated) { - const auto * ast = engine_args[0]->As(); + const auto * ast = engine_args[0]->as(); if (ast && ast->value.getType() == Field::Types::String) zookeeper_path = safeGet(ast->value); else @@ -484,7 +484,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) "Path in ZooKeeper must be a string literal" + getMergeTreeVerboseHelp(is_extended_storage_def), ErrorCodes::BAD_ARGUMENTS); - ast = engine_args[1]->As(); + ast = engine_args[1]->as(); if (ast && ast->value.getType() == Field::Types::String) replica_name = safeGet(ast->value); else @@ -512,7 +512,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) else if (merging_params.mode == MergeTreeData::MergingParams::Replacing) { /// If the last element is not index_granularity or replica_name (a literal), then this is the name of the version column. - if (!engine_args.empty() && !engine_args.back()->As()) + if (!engine_args.empty() && !engine_args.back()->as()) { if (!getIdentifierName(engine_args.back(), merging_params.version_column)) throw Exception( @@ -525,7 +525,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) else if (merging_params.mode == MergeTreeData::MergingParams::Summing) { /// If the last element is not index_granularity or replica_name (a literal), then this is a list of summable columns. - if (!engine_args.empty() && !engine_args.back()->As()) + if (!engine_args.empty() && !engine_args.back()->as()) { merging_params.columns_to_sum = extractColumnNames(engine_args.back()); engine_args.pop_back(); @@ -537,7 +537,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) String error_msg = "Last parameter of GraphiteMergeTree must be name (in single quotes) of element in configuration file with Graphite options"; error_msg += getMergeTreeVerboseHelp(is_extended_storage_def); - if (const auto * ast = engine_args.back()->As()) + if (const auto * ast = engine_args.back()->as()) { if (ast->value.getType() != Field::Types::String) throw Exception(error_msg, ErrorCodes::BAD_ARGUMENTS); @@ -618,7 +618,7 @@ static StoragePtr create(const StorageFactory::Arguments & args) order_by_ast = engine_args[1]; - const auto * ast = engine_args.back()->As(); + const auto * ast = engine_args.back()->as(); if (ast && ast->value.getType() == Field::Types::UInt64) storage_settings.index_granularity = safeGet(ast->value); else diff --git a/dbms/src/Storages/MutationCommands.cpp b/dbms/src/Storages/MutationCommands.cpp index f66f492c978..5e85a597150 100644 --- a/dbms/src/Storages/MutationCommands.cpp +++ b/dbms/src/Storages/MutationCommands.cpp @@ -35,7 +35,7 @@ std::optional MutationCommand::parse(ASTAlterCommand * command) res.predicate = command->predicate; for (const ASTPtr & assignment_ast : command->update_assignments->children) { - const auto * assignment = assignment_ast->As(); + const auto * assignment = assignment_ast->as(); auto insertion = res.column_to_update_expression.emplace(assignment->column_name, assignment->expression); if (!insertion.second) throw Exception("Multiple assignments in the single statement to column `" + assignment->column_name + "`", @@ -71,7 +71,7 @@ void MutationCommands::readText(ReadBuffer & in) ParserAlterCommandList p_alter_commands; auto commands_ast = parseQuery( p_alter_commands, commands_str.data(), commands_str.data() + commands_str.length(), "mutation commands list", 0); - for (ASTAlterCommand * command_ast : commands_ast->As()->commands) + for (ASTAlterCommand * command_ast : commands_ast->as()->commands) { auto command = MutationCommand::parse(command_ast); if (!command) diff --git a/dbms/src/Storages/StorageBuffer.cpp b/dbms/src/Storages/StorageBuffer.cpp index 35f9ea1f1e9..0fdb8d056d4 100644 --- a/dbms/src/Storages/StorageBuffer.cpp +++ b/dbms/src/Storages/StorageBuffer.cpp @@ -713,17 +713,17 @@ void registerStorageBuffer(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); - String destination_database = engine_args[0]->As()->value.safeGet(); - String destination_table = engine_args[1]->As()->value.safeGet(); + String destination_database = engine_args[0]->as()->value.safeGet(); + String destination_table = engine_args[1]->as()->value.safeGet(); - UInt64 num_buckets = applyVisitor(FieldVisitorConvertToNumber(), engine_args[2]->As()->value); + UInt64 num_buckets = applyVisitor(FieldVisitorConvertToNumber(), engine_args[2]->as()->value); - Int64 min_time = applyVisitor(FieldVisitorConvertToNumber(), engine_args[3]->As()->value); - Int64 max_time = applyVisitor(FieldVisitorConvertToNumber(), engine_args[4]->As()->value); - UInt64 min_rows = applyVisitor(FieldVisitorConvertToNumber(), engine_args[5]->As()->value); - UInt64 max_rows = applyVisitor(FieldVisitorConvertToNumber(), engine_args[6]->As()->value); - UInt64 min_bytes = applyVisitor(FieldVisitorConvertToNumber(), engine_args[7]->As()->value); - UInt64 max_bytes = applyVisitor(FieldVisitorConvertToNumber(), engine_args[8]->As()->value); + Int64 min_time = applyVisitor(FieldVisitorConvertToNumber(), engine_args[3]->as()->value); + Int64 max_time = applyVisitor(FieldVisitorConvertToNumber(), engine_args[4]->as()->value); + UInt64 min_rows = applyVisitor(FieldVisitorConvertToNumber(), engine_args[5]->as()->value); + UInt64 max_rows = applyVisitor(FieldVisitorConvertToNumber(), engine_args[6]->as()->value); + UInt64 min_bytes = applyVisitor(FieldVisitorConvertToNumber(), engine_args[7]->as()->value); + UInt64 max_bytes = applyVisitor(FieldVisitorConvertToNumber(), engine_args[8]->as()->value); return StorageBuffer::create( args.table_name, args.columns, diff --git a/dbms/src/Storages/StorageDictionary.cpp b/dbms/src/Storages/StorageDictionary.cpp index 644d1cb1378..3ad562543fd 100644 --- a/dbms/src/Storages/StorageDictionary.cpp +++ b/dbms/src/Storages/StorageDictionary.cpp @@ -101,7 +101,7 @@ void registerStorageDictionary(StorageFactory & factory) ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); args.engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(args.engine_args[0], args.local_context); - String dictionary_name = args.engine_args[0]->As()->value.safeGet(); + String dictionary_name = args.engine_args[0]->as()->value.safeGet(); return StorageDictionary::create( args.table_name, args.columns, args.context, args.attach, dictionary_name); diff --git a/dbms/src/Storages/StorageDistributed.cpp b/dbms/src/Storages/StorageDistributed.cpp index 4960b6c9b05..5ea027ba1f7 100644 --- a/dbms/src/Storages/StorageDistributed.cpp +++ b/dbms/src/Storages/StorageDistributed.cpp @@ -75,9 +75,9 @@ ASTPtr rewriteSelectQuery(const ASTPtr & query, const std::string & database, co { auto modified_query_ast = query->clone(); if (table_function_ptr) - modified_query_ast->As()->addTableFunction(table_function_ptr); + modified_query_ast->as()->addTableFunction(table_function_ptr); else - modified_query_ast->As()->replaceDatabaseAndTable(database, table); + modified_query_ast->as()->replaceDatabaseAndTable(database, table); return modified_query_ast; } @@ -468,7 +468,7 @@ void StorageDistributed::ClusterNodeData::shutdownAndDropAllData() /// using constraints from "WHERE" condition, otherwise returns `nullptr` ClusterPtr StorageDistributed::skipUnusedShards(ClusterPtr cluster, const SelectQueryInfo & query_info) { - const auto * select = query_info.query->As(); + const auto * select = query_info.query->as(); if (!select->where_expression) { @@ -528,8 +528,8 @@ void registerStorageDistributed(StorageFactory & factory) engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); engine_args[2] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[2], args.local_context); - String remote_database = engine_args[1]->As()->value.safeGet(); - String remote_table = engine_args[2]->As()->value.safeGet(); + String remote_database = engine_args[1]->as()->value.safeGet(); + String remote_table = engine_args[2]->as()->value.safeGet(); const auto & sharding_key = engine_args.size() == 4 ? engine_args[3] : nullptr; diff --git a/dbms/src/Storages/StorageFile.cpp b/dbms/src/Storages/StorageFile.cpp index 12279cfcd5a..04b4c3853f8 100644 --- a/dbms/src/Storages/StorageFile.cpp +++ b/dbms/src/Storages/StorageFile.cpp @@ -291,7 +291,7 @@ void registerStorageFile(StorageFactory & factory) ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); - String format_name = engine_args[0]->As()->value.safeGet(); + String format_name = engine_args[0]->as()->value.safeGet(); int source_fd = -1; String source_path; @@ -311,7 +311,7 @@ void registerStorageFile(StorageFactory & factory) throw Exception("Unknown identifier '" + *opt_name + "' in second arg of File storage constructor", ErrorCodes::UNKNOWN_IDENTIFIER); } - else if (const auto * literal = engine_args[1]->As()) + else if (const auto * literal = engine_args[1]->as()) { auto type = literal->value.getType(); if (type == Field::Types::Int64) diff --git a/dbms/src/Storages/StorageHDFS.cpp b/dbms/src/Storages/StorageHDFS.cpp index 7bc6ee54062..b7607112acb 100644 --- a/dbms/src/Storages/StorageHDFS.cpp +++ b/dbms/src/Storages/StorageHDFS.cpp @@ -163,11 +163,11 @@ void registerStorageHDFS(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); - String url = engine_args[0]->As()->value.safeGet(); + String url = engine_args[0]->as()->value.safeGet(); engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); - String format_name = engine_args[0]->As()->value.safeGet(); + String format_name = engine_args[0]->as()->value.safeGet(); return StorageHDFS::create(url, args.table_name, format_name, args.columns, args.context); }); diff --git a/dbms/src/Storages/StorageMaterializedView.cpp b/dbms/src/Storages/StorageMaterializedView.cpp index a1ab2c03d73..5ef142f6857 100644 --- a/dbms/src/Storages/StorageMaterializedView.cpp +++ b/dbms/src/Storages/StorageMaterializedView.cpp @@ -48,14 +48,14 @@ static void extractDependentTable(ASTSelectQuery & query, String & select_databa else select_database_name = db_and_table->database; } - else if (auto * ast_select = subquery->As()) + else if (auto * ast_select = subquery->as()) { if (ast_select->list_of_selects->children.size() != 1) throw Exception("UNION is not supported for MATERIALIZED VIEW", ErrorCodes::QUERY_IS_NOT_SUPPORTED_IN_MATERIALIZED_VIEW); auto & inner_query = ast_select->list_of_selects->children.at(0); - extractDependentTable(*inner_query->As(), select_database_name, select_table_name); + extractDependentTable(*inner_query->as(), select_database_name, select_table_name); } else throw Exception("Logical error while creating StorageMaterializedView." @@ -73,14 +73,14 @@ static void checkAllowedQueries(const ASTSelectQuery & query) if (!subquery) return; - if (const auto * ast_select = subquery->As()) + if (const auto * ast_select = subquery->as()) { if (ast_select->list_of_selects->children.size() != 1) throw Exception("UNION is not supported for MATERIALIZED VIEW", ErrorCodes::QUERY_IS_NOT_SUPPORTED_IN_MATERIALIZED_VIEW); const auto & inner_query = ast_select->list_of_selects->children.at(0); - checkAllowedQueries(*inner_query->As()); + checkAllowedQueries(*inner_query->as()); } } @@ -110,7 +110,7 @@ StorageMaterializedView::StorageMaterializedView( inner_query = query.select->list_of_selects->children.at(0); - auto * select_query = inner_query->As(); + auto * select_query = inner_query->as(); extractDependentTable(*select_query, select_database_name, select_table_name); checkAllowedQueries(*select_query); diff --git a/dbms/src/Storages/StorageMerge.cpp b/dbms/src/Storages/StorageMerge.cpp index 35da76e7d9e..0622020bc58 100644 --- a/dbms/src/Storages/StorageMerge.cpp +++ b/dbms/src/Storages/StorageMerge.cpp @@ -289,7 +289,7 @@ BlockInputStreams StorageMerge::createSourceStreams(const SelectQueryInfo & quer } else if (processed_stage > storage->getQueryProcessingStage(modified_context)) { - modified_query_info.query->As()->replaceDatabaseAndTable(source_database, storage->getTableName()); + modified_query_info.query->as()->replaceDatabaseAndTable(source_database, storage->getTableName()); /// Maximum permissible parallelism is streams_num modified_context.getSettingsRef().max_threads = UInt64(streams_num); @@ -369,7 +369,7 @@ StorageMerge::StorageListWithLocks StorageMerge::getSelectedTables(const ASTPtr { StoragePtr storage = iterator->table(); - if (query && query->As()->prewhere_expression && !storage->supportsPrewhere()) + if (query && query->as()->prewhere_expression && !storage->supportsPrewhere()) throw Exception("Storage " + storage->getName() + " doesn't support PREWHERE.", ErrorCodes::ILLEGAL_PREWHERE); if (storage.get() != this) @@ -440,7 +440,7 @@ void StorageMerge::convertingSourceStream(const Block & header, const Context & Block before_block_header = source_stream->getHeader(); source_stream = std::make_shared(context, source_stream, header, ConvertingBlockInputStream::MatchColumnsMode::Name); - auto where_expression = query->As()->where_expression; + auto where_expression = query->as()->where_expression; if (!where_expression) return; @@ -491,8 +491,8 @@ void registerStorageMerge(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); engine_args[1] = evaluateConstantExpressionAsLiteral(engine_args[1], args.local_context); - String source_database = engine_args[0]->As()->value.safeGet(); - String table_name_regexp = engine_args[1]->As()->value.safeGet(); + String source_database = engine_args[0]->as()->value.safeGet(); + String table_name_regexp = engine_args[1]->as()->value.safeGet(); return StorageMerge::create( args.table_name, args.columns, diff --git a/dbms/src/Storages/StorageMergeTree.cpp b/dbms/src/Storages/StorageMergeTree.cpp index 8a90d85f8bc..44264b691b7 100644 --- a/dbms/src/Storages/StorageMergeTree.cpp +++ b/dbms/src/Storages/StorageMergeTree.cpp @@ -235,7 +235,7 @@ void StorageMergeTree::alter( IDatabase::ASTModifier storage_modifier = [&] (IAST & ast) { - auto * storage_ast = ast.As(); + auto * storage_ast = ast.as(); if (new_order_by_ast.get() != data.order_by_ast.get()) storage_ast->set(storage_ast->order_by, new_order_by_ast); @@ -941,7 +941,7 @@ void StorageMergeTree::attachPartition(const ASTPtr & partition, bool attach_par String partition_id; if (attach_part) - partition_id = partition->As()->value.safeGet(); + partition_id = partition->as()->value.safeGet(); else partition_id = data.getPartitionIDFromQuery(partition, context); diff --git a/dbms/src/Storages/StorageMySQL.cpp b/dbms/src/Storages/StorageMySQL.cpp index 3bb1799ef50..2d06d032935 100644 --- a/dbms/src/Storages/StorageMySQL.cpp +++ b/dbms/src/Storages/StorageMySQL.cpp @@ -199,21 +199,21 @@ void registerStorageMySQL(StorageFactory & factory) engine_args[i] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[i], args.local_context); /// 3306 is the default MySQL port. - auto parsed_host_port = parseAddress(engine_args[0]->As()->value.safeGet(), 3306); + auto parsed_host_port = parseAddress(engine_args[0]->as()->value.safeGet(), 3306); - const String & remote_database = engine_args[1]->As()->value.safeGet(); - const String & remote_table = engine_args[2]->As()->value.safeGet(); - const String & username = engine_args[3]->As()->value.safeGet(); - const String & password = engine_args[4]->As()->value.safeGet(); + const String & remote_database = engine_args[1]->as()->value.safeGet(); + const String & remote_table = engine_args[2]->as()->value.safeGet(); + const String & username = engine_args[3]->as()->value.safeGet(); + const String & password = engine_args[4]->as()->value.safeGet(); mysqlxx::Pool pool(remote_database, parsed_host_port.first, username, password, parsed_host_port.second); bool replace_query = false; std::string on_duplicate_clause; if (engine_args.size() >= 6) - replace_query = engine_args[5]->As()->value.safeGet(); + replace_query = engine_args[5]->as()->value.safeGet(); if (engine_args.size() == 7) - on_duplicate_clause = engine_args[6]->As()->value.safeGet(); + on_duplicate_clause = engine_args[6]->as()->value.safeGet(); if (replace_query && !on_duplicate_clause.empty()) throw Exception( diff --git a/dbms/src/Storages/StorageReplicatedMergeTree.cpp b/dbms/src/Storages/StorageReplicatedMergeTree.cpp index ff858e3da4b..f02c1b7a915 100644 --- a/dbms/src/Storages/StorageReplicatedMergeTree.cpp +++ b/dbms/src/Storages/StorageReplicatedMergeTree.cpp @@ -447,7 +447,7 @@ void StorageReplicatedMergeTree::setTableStructure(ColumnsDescription new_column storage_modifier = [&](IAST & ast) { - auto * storage_ast = ast.As(); + auto * storage_ast = ast.as(); if (!storage_ast->order_by) throw Exception( @@ -3558,7 +3558,7 @@ void StorageReplicatedMergeTree::attachPartition(const ASTPtr & partition, bool String partition_id; if (attach_part) - partition_id = partition->As()->value.safeGet(); + partition_id = partition->as()->value.safeGet(); else partition_id = data.getPartitionIDFromQuery(partition, query_context); @@ -3977,17 +3977,17 @@ void StorageReplicatedMergeTree::sendRequestToLeaderReplica(const ASTPtr & query /// TODO: add setters and getters interface for database and table fields of AST auto new_query = query->clone(); - if (auto * alter = new_query->As()) + if (auto * alter = new_query->as()) { alter->database = leader_address.database; alter->table = leader_address.table; } - else if (auto * optimize = new_query->As()) + else if (auto * optimize = new_query->as()) { optimize->database = leader_address.database; optimize->table = leader_address.table; } - else if (auto * drop = new_query->As(); drop->kind == ASTDropQuery::Kind::Truncate) + else if (auto * drop = new_query->as(); drop->kind == ASTDropQuery::Kind::Truncate) { drop->database = leader_address.database; drop->table = leader_address.table; diff --git a/dbms/src/Storages/StorageURL.cpp b/dbms/src/Storages/StorageURL.cpp index 7a60f22926f..3a4313099b2 100644 --- a/dbms/src/Storages/StorageURL.cpp +++ b/dbms/src/Storages/StorageURL.cpp @@ -202,12 +202,12 @@ void registerStorageURL(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); - String url = engine_args[0]->As()->value.safeGet(); + String url = engine_args[0]->as()->value.safeGet(); Poco::URI uri(url); engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); - String format_name = engine_args[1]->As()->value.safeGet(); + String format_name = engine_args[1]->as()->value.safeGet(); return StorageURL::create(uri, args.table_name, format_name, args.columns, args.context); }); diff --git a/dbms/src/Storages/StorageView.cpp b/dbms/src/Storages/StorageView.cpp index ac0a3efadbe..dec57408746 100644 --- a/dbms/src/Storages/StorageView.cpp +++ b/dbms/src/Storages/StorageView.cpp @@ -54,7 +54,7 @@ BlockInputStreams StorageView::read( { auto new_inner_query = inner_query->clone(); auto new_outer_query = query_info.query->clone(); - auto * new_outer_select = new_outer_query->As(); + auto * new_outer_select = new_outer_query->as(); replaceTableNameWithSubquery(new_outer_select, new_inner_query); @@ -74,12 +74,12 @@ BlockInputStreams StorageView::read( void StorageView::replaceTableNameWithSubquery(ASTSelectQuery * select_query, ASTPtr & subquery) { - auto * select_element = select_query->tables->children[0]->As(); + auto * select_element = select_query->tables->children[0]->as(); if (!select_element->table_expression) throw Exception("Logical error: incorrect table expression", ErrorCodes::LOGICAL_ERROR); - auto * table_expression = select_element->table_expression->As(); + auto * table_expression = select_element->table_expression->as(); if (!table_expression->database_and_table_name) throw Exception("Logical error: incorrect table expression", ErrorCodes::LOGICAL_ERROR); diff --git a/dbms/src/Storages/StorageXDBC.cpp b/dbms/src/Storages/StorageXDBC.cpp index c1c49773eed..e2f7e7975df 100644 --- a/dbms/src/Storages/StorageXDBC.cpp +++ b/dbms/src/Storages/StorageXDBC.cpp @@ -115,10 +115,10 @@ namespace BridgeHelperPtr bridge_helper = std::make_shared>(args.context, args.context.getSettingsRef().http_receive_timeout.value, - engine_args[0]->As()->value.safeGet()); + engine_args[0]->as()->value.safeGet()); return std::make_shared(args.table_name, - engine_args[1]->As()->value.safeGet(), - engine_args[2]->As()->value.safeGet(), + engine_args[1]->as()->value.safeGet(), + engine_args[2]->as()->value.safeGet(), args.columns, args.context, bridge_helper); diff --git a/dbms/src/Storages/System/StorageSystemTables.cpp b/dbms/src/Storages/System/StorageSystemTables.cpp index 0499b376d0a..85fa9c2a0fa 100644 --- a/dbms/src/Storages/System/StorageSystemTables.cpp +++ b/dbms/src/Storages/System/StorageSystemTables.cpp @@ -240,7 +240,7 @@ protected: if (ast) { - const auto * ast_create = ast->As(); + const auto * ast_create = ast->as(); if (ast_create->storage) { engine_full = queryToString(*ast_create->storage); diff --git a/dbms/src/Storages/System/StorageSystemZooKeeper.cpp b/dbms/src/Storages/System/StorageSystemZooKeeper.cpp index 5892967ce39..7533e88aa21 100644 --- a/dbms/src/Storages/System/StorageSystemZooKeeper.cpp +++ b/dbms/src/Storages/System/StorageSystemZooKeeper.cpp @@ -44,7 +44,7 @@ NamesAndTypesList StorageSystemZooKeeper::getNamesAndTypes() static bool extractPathImpl(const IAST & elem, String & res) { - const auto * function = elem.As(); + const auto * function = elem.as(); if (!function) return false; @@ -59,16 +59,16 @@ static bool extractPathImpl(const IAST & elem, String & res) if (function->name == "equals") { - const auto * args = function->arguments->As(); + const auto * args = function->arguments->as(); const IAST * value; if (args->children.size() != 2) return false; const ASTIdentifier * ident; - if ((ident = args->children.at(0)->As())) + if ((ident = args->children.at(0)->as())) value = &*args->children.at(1); - else if ((ident = args->children.at(1)->As())) + else if ((ident = args->children.at(1)->as())) value = &*args->children.at(0); else return false; @@ -76,7 +76,7 @@ static bool extractPathImpl(const IAST & elem, String & res) if (ident->name != "path") return false; - const auto * literal = value->As(); + const auto * literal = value->as(); if (!literal) return false; @@ -95,7 +95,7 @@ static bool extractPathImpl(const IAST & elem, String & res) */ static String extractPath(const ASTPtr & query) { - const auto * select = query->As(); + const auto * select = query->as(); if (!select->where_expression) return ""; diff --git a/dbms/src/Storages/VirtualColumnUtils.cpp b/dbms/src/Storages/VirtualColumnUtils.cpp index 6da2bdc921b..43ca07e5a98 100644 --- a/dbms/src/Storages/VirtualColumnUtils.cpp +++ b/dbms/src/Storages/VirtualColumnUtils.cpp @@ -76,14 +76,14 @@ String chooseSuffixForSet(const NamesAndTypesList & columns, const std::vectorAs(); + auto * select = ast->as(); if (!select->with_expression_list) { select->with_expression_list = std::make_shared(); select->children.insert(select->children.begin(), select->with_expression_list); } - auto * with = select->with_expression_list->As(); + auto * with = select->with_expression_list->as(); auto literal = std::make_shared(value); literal->alias = column_name; literal->prefer_alias_to_column_name = true; @@ -106,7 +106,7 @@ static bool isValidFunction(const ASTPtr & expression, const NameSet & columns) /// Extract all subfunctions of the main conjunction, but depending only on the specified columns static void extractFunctions(const ASTPtr & expression, const NameSet & columns, std::vector & result) { - const auto * function = expression->As(); + const auto * function = expression->as(); if (function && function->name == "and") { for (size_t i = 0; i < function->arguments->children.size(); ++i) @@ -126,7 +126,7 @@ static ASTPtr buildWhereExpression(const ASTs & functions) if (functions.size() == 1) return functions[0]; ASTPtr new_query = std::make_shared(); - auto * new_function = new_query->As(); + auto * new_function = new_query->as(); new_function->name = "and"; new_function->arguments = std::make_shared(); new_function->arguments->children = functions; @@ -136,7 +136,7 @@ static ASTPtr buildWhereExpression(const ASTs & functions) void filterBlockWithQuery(const ASTPtr & query, Block & block, const Context & context) { - const auto * select = query->As(); + const auto * select = query->as(); if (!select->where_expression && !select->prewhere_expression) return; diff --git a/dbms/src/Storages/getStructureOfRemoteTable.cpp b/dbms/src/Storages/getStructureOfRemoteTable.cpp index c606a620c5f..e6e8cea7f78 100644 --- a/dbms/src/Storages/getStructureOfRemoteTable.cpp +++ b/dbms/src/Storages/getStructureOfRemoteTable.cpp @@ -39,7 +39,7 @@ ColumnsDescription getStructureOfRemoteTable( { if (shard_info.isLocal()) { - const auto * table_function = table_func_ptr->As(); + const auto * table_function = table_func_ptr->as(); return TableFunctionFactory::instance().get(table_function->name, context)->execute(table_func_ptr, context)->getColumns(); } diff --git a/dbms/src/Storages/transformQueryForExternalDatabase.cpp b/dbms/src/Storages/transformQueryForExternalDatabase.cpp index b14420884b6..4e257cf63ae 100644 --- a/dbms/src/Storages/transformQueryForExternalDatabase.cpp +++ b/dbms/src/Storages/transformQueryForExternalDatabase.cpp @@ -21,10 +21,10 @@ static void replaceConstFunction(IAST & node, const Context & context, const Nam for (size_t i = 0; i < node.children.size(); ++i) { auto child = node.children[i]; - if (auto * exp_list = child->As()) + if (auto * exp_list = child->as()) replaceConstFunction(*exp_list, context, all_columns); - if (auto * function = child->As()) + if (auto * function = child->as()) { NamesAndTypesList source_columns = all_columns; ASTPtr query = function->ptr(); @@ -42,7 +42,7 @@ static void replaceConstFunction(IAST & node, const Context & context, const Nam static bool isCompatible(const IAST & node) { - if (const auto * function = node.As()) + if (const auto * function = node.as()) { String name = function->name; if (!(name == "and" @@ -66,7 +66,7 @@ static bool isCompatible(const IAST & node) return true; } - if (const auto * literal = node.As()) + if (const auto * literal = node.as()) { /// Foreign databases often have no support for Array and Tuple literals. if (literal->value.getType() == Field::Types::Array @@ -76,7 +76,7 @@ static bool isCompatible(const IAST & node) return true; } - if (node.As()) + if (node.as()) return true; return false; @@ -112,7 +112,7 @@ String transformQueryForExternalDatabase( * copy only compatible parts of it. */ - auto & original_where = clone_query->As()->where_expression; + auto & original_where = clone_query->as()->where_expression; if (original_where) { replaceConstFunction(*original_where, context, available_columns); @@ -120,7 +120,7 @@ String transformQueryForExternalDatabase( { select->where_expression = original_where; } - else if (const auto * function = original_where->As()) + else if (const auto * function = original_where->as()) { if (function->name == "and") { diff --git a/dbms/src/TableFunctions/ITableFunctionFileLike.cpp b/dbms/src/TableFunctions/ITableFunctionFileLike.cpp index 6f9e4ddd3d5..0ef6139fdbc 100644 --- a/dbms/src/TableFunctions/ITableFunctionFileLike.cpp +++ b/dbms/src/TableFunctions/ITableFunctionFileLike.cpp @@ -36,9 +36,9 @@ StoragePtr ITableFunctionFileLike::executeImpl(const ASTPtr & ast_function, cons for (size_t i = 0; i < 3; ++i) args[i] = evaluateConstantExpressionOrIdentifierAsLiteral(args[i], context); - std::string filename = args[0]->As()->value.safeGet(); - std::string format = args[1]->As()->value.safeGet(); - std::string structure = args[2]->As()->value.safeGet(); + std::string filename = args[0]->as()->value.safeGet(); + std::string format = args[1]->as()->value.safeGet(); + std::string structure = args[2]->as()->value.safeGet(); // Create sample block std::vector structure_vals; diff --git a/dbms/src/TableFunctions/ITableFunctionXDBC.cpp b/dbms/src/TableFunctions/ITableFunctionXDBC.cpp index df4686ab740..9476946dc85 100644 --- a/dbms/src/TableFunctions/ITableFunctionXDBC.cpp +++ b/dbms/src/TableFunctions/ITableFunctionXDBC.cpp @@ -29,7 +29,7 @@ namespace ErrorCodes StoragePtr ITableFunctionXDBC::executeImpl(const ASTPtr & ast_function, const Context & context) const { - const auto * args_func = ast_function->As(); + const auto * args_func = ast_function->as(); if (!args_func->arguments) throw Exception("Table function '" + getName() + "' must have arguments.", ErrorCodes::LOGICAL_ERROR); @@ -49,14 +49,14 @@ StoragePtr ITableFunctionXDBC::executeImpl(const ASTPtr & ast_function, const Co if (args.size() == 3) { - connection_string = args[0]->As()->value.safeGet(); - schema_name = args[1]->As()->value.safeGet(); - table_name = args[2]->As()->value.safeGet(); + connection_string = args[0]->as()->value.safeGet(); + schema_name = args[1]->as()->value.safeGet(); + table_name = args[2]->as()->value.safeGet(); } else if (args.size() == 2) { - connection_string = args[0]->As()->value.safeGet(); - table_name = args[1]->As()->value.safeGet(); + connection_string = args[0]->as()->value.safeGet(); + table_name = args[1]->as()->value.safeGet(); } /* Infer external table structure */ diff --git a/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp b/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp index 94b4b0d4446..23ff34be827 100644 --- a/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp +++ b/dbms/src/TableFunctions/TableFunctionCatBoostPool.cpp @@ -33,7 +33,7 @@ StoragePtr TableFunctionCatBoostPool::executeImpl(const ASTPtr & ast_function, c auto getStringLiteral = [](const IAST & node, const char * description) { - const auto * lit = node.As(); + const auto * lit = node.as(); if (!lit) throw Exception(description + String(" must be string literal (in single quotes)."), ErrorCodes::BAD_ARGUMENTS); diff --git a/dbms/src/TableFunctions/TableFunctionMerge.cpp b/dbms/src/TableFunctions/TableFunctionMerge.cpp index 9c7bfa37edc..eda2720a7bc 100644 --- a/dbms/src/TableFunctions/TableFunctionMerge.cpp +++ b/dbms/src/TableFunctions/TableFunctionMerge.cpp @@ -73,8 +73,8 @@ StoragePtr TableFunctionMerge::executeImpl(const ASTPtr & ast_function, const Co args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(args[0], context); args[1] = evaluateConstantExpressionAsLiteral(args[1], context); - String source_database = args[0]->As()->value.safeGet(); - String table_name_regexp = args[1]->As()->value.safeGet(); + String source_database = args[0]->as()->value.safeGet(); + String table_name_regexp = args[1]->as()->value.safeGet(); auto res = StorageMerge::create( getName(), diff --git a/dbms/src/TableFunctions/TableFunctionMySQL.cpp b/dbms/src/TableFunctions/TableFunctionMySQL.cpp index 1d3ad537850..ad1aac5744e 100644 --- a/dbms/src/TableFunctions/TableFunctionMySQL.cpp +++ b/dbms/src/TableFunctions/TableFunctionMySQL.cpp @@ -87,7 +87,7 @@ DataTypePtr getDataType(const String & mysql_data_type, bool is_nullable, bool i StoragePtr TableFunctionMySQL::executeImpl(const ASTPtr & ast_function, const Context & context) const { - const auto * args_func = ast_function->As(); + const auto * args_func = ast_function->as(); if (!args_func->arguments) throw Exception("Table function 'mysql' must have arguments.", ErrorCodes::LOGICAL_ERROR); @@ -101,18 +101,18 @@ StoragePtr TableFunctionMySQL::executeImpl(const ASTPtr & ast_function, const Co for (size_t i = 0; i < args.size(); ++i) args[i] = evaluateConstantExpressionOrIdentifierAsLiteral(args[i], context); - std::string host_port = args[0]->As()->value.safeGet(); - std::string database_name = args[1]->As()->value.safeGet(); - std::string table_name = args[2]->As()->value.safeGet(); - std::string user_name = args[3]->As()->value.safeGet(); - std::string password = args[4]->As()->value.safeGet(); + std::string host_port = args[0]->as()->value.safeGet(); + std::string database_name = args[1]->as()->value.safeGet(); + std::string table_name = args[2]->as()->value.safeGet(); + std::string user_name = args[3]->as()->value.safeGet(); + std::string password = args[4]->as()->value.safeGet(); bool replace_query = false; std::string on_duplicate_clause; if (args.size() >= 6) - replace_query = args[5]->As()->value.safeGet() > 0; + replace_query = args[5]->as()->value.safeGet() > 0; if (args.size() == 7) - on_duplicate_clause = args[6]->As()->value.safeGet(); + on_duplicate_clause = args[6]->as()->value.safeGet(); if (replace_query && !on_duplicate_clause.empty()) throw Exception( diff --git a/dbms/src/TableFunctions/TableFunctionNumbers.cpp b/dbms/src/TableFunctions/TableFunctionNumbers.cpp index 56a76b096ba..839d6eb363d 100644 --- a/dbms/src/TableFunctions/TableFunctionNumbers.cpp +++ b/dbms/src/TableFunctions/TableFunctionNumbers.cpp @@ -19,7 +19,7 @@ namespace ErrorCodes StoragePtr TableFunctionNumbers::executeImpl(const ASTPtr & ast_function, const Context & context) const { - if (const auto * function = ast_function->As()) + if (const auto * function = ast_function->as()) { auto arguments = function->arguments->children; @@ -45,7 +45,7 @@ void registerTableFunctionNumbers(TableFunctionFactory & factory) UInt64 TableFunctionNumbers::evaluateArgument(const Context & context, ASTPtr & argument) const { - return evaluateConstantExpressionOrIdentifierAsLiteral(argument, context)->As()->value.safeGet(); + return evaluateConstantExpressionOrIdentifierAsLiteral(argument, context)->as()->value.safeGet(); } } diff --git a/dbms/src/TableFunctions/TableFunctionRemote.cpp b/dbms/src/TableFunctions/TableFunctionRemote.cpp index c8a5febbf51..1f552f6bef8 100644 --- a/dbms/src/TableFunctions/TableFunctionRemote.cpp +++ b/dbms/src/TableFunctions/TableFunctionRemote.cpp @@ -50,7 +50,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C auto getStringLiteral = [](const IAST & node, const char * description) { - const auto * lit = node.As(); + const auto * lit = node.as(); if (!lit) throw Exception(description + String(" must be string literal (in single quotes)."), ErrorCodes::BAD_ARGUMENTS); @@ -63,7 +63,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C if (is_cluster_function) { ASTPtr ast_name = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context); - cluster_name = ast_name->As()->value.safeGet(); + cluster_name = ast_name->as()->value.safeGet(); } else { @@ -74,7 +74,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C args[arg_num] = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context); - const auto * function = args[arg_num]->As(); + const auto * function = args[arg_num]->as(); if (function && TableFunctionFactory::instance().isTableFunctionName(function->name)) { @@ -83,7 +83,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C } else { - remote_database = args[arg_num]->As()->value.safeGet(); + remote_database = args[arg_num]->as()->value.safeGet(); ++arg_num; @@ -103,7 +103,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C else { args[arg_num] = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context); - remote_table = args[arg_num]->As()->value.safeGet(); + remote_table = args[arg_num]->as()->value.safeGet(); ++arg_num; } } From a3a8b2bbf77c094359d8a1bc5b14dc6d26671cb8 Mon Sep 17 00:00:00 2001 From: Ivan Lezhankin Date: Mon, 11 Mar 2019 17:01:45 +0300 Subject: [PATCH 04/11] Include IAST_fwd.h for using ASTPtr --- dbms/src/Compression/CompressionFactory.h | 19 +++++++------ dbms/src/DataTypes/DataTypeFactory.h | 14 +++++----- dbms/src/Databases/IDatabase.h | 18 ++++++------- dbms/src/Interpreters/Aliases.h | 8 +++--- dbms/src/Interpreters/Context.h | 27 +++++++++---------- .../Interpreters/DatabaseAndTableWithAlias.h | 10 +++---- dbms/src/Interpreters/ExpressionAnalyzer.h | 7 +++-- dbms/src/Interpreters/InterpreterAlterQuery.h | 3 +-- .../Interpreters/InterpreterDescribeQuery.h | 3 +-- dbms/src/Interpreters/InterpreterDropQuery.h | 6 ++--- .../src/Interpreters/InterpreterExistsQuery.h | 3 +-- .../Interpreters/InterpreterExplainQuery.h | 5 +--- dbms/src/Interpreters/InterpreterFactory.h | 3 +-- .../Interpreters/InterpreterKillQueryQuery.h | 4 +-- .../Interpreters/InterpreterOptimizeQuery.h | 3 +-- .../src/Interpreters/InterpreterRenameQuery.h | 3 +-- .../Interpreters/InterpreterSelectQuery.cpp | 6 +++-- dbms/src/Interpreters/InterpreterSetQuery.h | 3 +-- .../Interpreters/InterpreterShowCreateQuery.h | 3 +-- .../InterpreterShowProcesslistQuery.h | 3 +-- .../Interpreters/InterpreterShowTablesQuery.h | 3 +-- .../src/Interpreters/InterpreterSystemQuery.h | 4 +-- dbms/src/Interpreters/InterpreterUseQuery.h | 3 +-- dbms/src/Storages/StorageMaterializedView.h | 5 +--- dbms/src/Storages/StorageView.h | 10 +++---- dbms/src/TableFunctions/ITableFunction.h | 5 ++-- 26 files changed, 76 insertions(+), 105 deletions(-) diff --git a/dbms/src/Compression/CompressionFactory.h b/dbms/src/Compression/CompressionFactory.h index db28a192011..b36bed1cf8e 100644 --- a/dbms/src/Compression/CompressionFactory.h +++ b/dbms/src/Compression/CompressionFactory.h @@ -1,14 +1,17 @@ #pragma once -#include +#include +#include +#include +#include +#include + +#include + #include +#include #include #include -#include -#include -#include -#include -#include namespace DB { @@ -19,10 +22,6 @@ using CompressionCodecPtr = std::shared_ptr; using CodecNameWithLevel = std::pair>; -class IAST; - -using ASTPtr = std::shared_ptr; - /** Creates a codec object by name of compression algorithm family and parameters. */ class CompressionCodecFactory final : public ext::singleton diff --git a/dbms/src/DataTypes/DataTypeFactory.h b/dbms/src/DataTypes/DataTypeFactory.h index 95cda9002f4..c6ef100bbb7 100644 --- a/dbms/src/DataTypes/DataTypeFactory.h +++ b/dbms/src/DataTypes/DataTypeFactory.h @@ -1,12 +1,15 @@ #pragma once -#include -#include -#include -#include #include +#include +#include + #include +#include +#include +#include + namespace DB { @@ -17,9 +20,6 @@ using DataTypePtr = std::shared_ptr; class IDataTypeDomain; using DataTypeDomainPtr = std::unique_ptr; -class IAST; -using ASTPtr = std::shared_ptr; - /** Creates a data type by name of data type family and parameters. */ diff --git a/dbms/src/Databases/IDatabase.h b/dbms/src/Databases/IDatabase.h index e6b67a87c9b..7c0d501fc60 100644 --- a/dbms/src/Databases/IDatabase.h +++ b/dbms/src/Databases/IDatabase.h @@ -1,16 +1,18 @@ #pragma once -#include #include +#include +#include +#include #include #include -#include -#include -#include #include -#include #include -#include +#include + +#include +#include +#include namespace DB @@ -21,9 +23,6 @@ class Context; class IStorage; using StoragePtr = std::shared_ptr; -class IAST; -using ASTPtr = std::shared_ptr; - struct Settings; @@ -157,4 +156,3 @@ using DatabasePtr = std::shared_ptr; using Databases = std::map; } - diff --git a/dbms/src/Interpreters/Aliases.h b/dbms/src/Interpreters/Aliases.h index 80976c7551f..52159442224 100644 --- a/dbms/src/Interpreters/Aliases.h +++ b/dbms/src/Interpreters/Aliases.h @@ -1,15 +1,13 @@ #pragma once -#include - #include +#include + +#include namespace DB { -class IAST; -using ASTPtr = std::shared_ptr; - using Aliases = std::unordered_map; } diff --git a/dbms/src/Interpreters/Context.h b/dbms/src/Interpreters/Context.h index 8b4e66094ff..4f90a50e349 100644 --- a/dbms/src/Interpreters/Context.h +++ b/dbms/src/Interpreters/Context.h @@ -1,23 +1,24 @@ #pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include #include #include #include #include #include -#include -#include #include - -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include namespace Poco @@ -68,8 +69,6 @@ class IStorage; class ITableFunction; using StoragePtr = std::shared_ptr; using Tables = std::map; -class IAST; -using ASTPtr = std::shared_ptr; class IBlockInputStream; class IBlockOutputStream; using BlockInputStreamPtr = std::shared_ptr; diff --git a/dbms/src/Interpreters/DatabaseAndTableWithAlias.h b/dbms/src/Interpreters/DatabaseAndTableWithAlias.h index 0f1cbe8bbc7..22b03a5ed44 100644 --- a/dbms/src/Interpreters/DatabaseAndTableWithAlias.h +++ b/dbms/src/Interpreters/DatabaseAndTableWithAlias.h @@ -1,18 +1,16 @@ #pragma once +#include +#include +#include + #include #include -#include -#include - namespace DB { -class IAST; -using ASTPtr = std::shared_ptr; - class ASTSelectQuery; class ASTIdentifier; struct ASTTableExpression; diff --git a/dbms/src/Interpreters/ExpressionAnalyzer.h b/dbms/src/Interpreters/ExpressionAnalyzer.h index c7441efe4cb..b9ec5c3ca70 100644 --- a/dbms/src/Interpreters/ExpressionAnalyzer.h +++ b/dbms/src/Interpreters/ExpressionAnalyzer.h @@ -1,9 +1,11 @@ #pragma once +#include #include #include -#include #include +#include + namespace DB { @@ -15,9 +17,6 @@ struct ExpressionActionsChain; class ExpressionActions; using ExpressionActionsPtr = std::shared_ptr; -class IAST; -using ASTPtr = std::shared_ptr; -using ASTs = std::vector; struct ASTTableJoin; class IBlockInputStream; diff --git a/dbms/src/Interpreters/InterpreterAlterQuery.h b/dbms/src/Interpreters/InterpreterAlterQuery.h index bd9f3a89d6a..776409a225d 100644 --- a/dbms/src/Interpreters/InterpreterAlterQuery.h +++ b/dbms/src/Interpreters/InterpreterAlterQuery.h @@ -1,14 +1,13 @@ #pragma once #include +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; /** Allows you add or remove a column in the table. * It also allows you to manipulate the partitions of the MergeTree family tables. diff --git a/dbms/src/Interpreters/InterpreterDescribeQuery.h b/dbms/src/Interpreters/InterpreterDescribeQuery.h index fc0bea10f2d..4fafe61f229 100644 --- a/dbms/src/Interpreters/InterpreterDescribeQuery.h +++ b/dbms/src/Interpreters/InterpreterDescribeQuery.h @@ -1,14 +1,13 @@ #pragma once #include +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; /** Return names, types and other information about columns in specified table. diff --git a/dbms/src/Interpreters/InterpreterDropQuery.h b/dbms/src/Interpreters/InterpreterDropQuery.h index 2bea9f85c99..1493d262a23 100644 --- a/dbms/src/Interpreters/InterpreterDropQuery.h +++ b/dbms/src/Interpreters/InterpreterDropQuery.h @@ -1,16 +1,14 @@ #pragma once +#include #include #include -#include - +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; using DatabaseAndTable = std::pair; /** Allow to either drop table with all its data (DROP), diff --git a/dbms/src/Interpreters/InterpreterExistsQuery.h b/dbms/src/Interpreters/InterpreterExistsQuery.h index b2050b443d8..1860e1d0aa9 100644 --- a/dbms/src/Interpreters/InterpreterExistsQuery.h +++ b/dbms/src/Interpreters/InterpreterExistsQuery.h @@ -1,14 +1,13 @@ #pragma once #include +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; /** Check that table exists. Return single row with single column "result" of type UInt8 and value 0 or 1. diff --git a/dbms/src/Interpreters/InterpreterExplainQuery.h b/dbms/src/Interpreters/InterpreterExplainQuery.h index 4db796ad014..0d3b183857b 100644 --- a/dbms/src/Interpreters/InterpreterExplainQuery.h +++ b/dbms/src/Interpreters/InterpreterExplainQuery.h @@ -2,15 +2,12 @@ #include #include +#include namespace DB { -class IAST; -using ASTPtr = std::shared_ptr; - - /// Returns single row with explain results class InterpreterExplainQuery : public IInterpreter { diff --git a/dbms/src/Interpreters/InterpreterFactory.h b/dbms/src/Interpreters/InterpreterFactory.h index 25bad6659d5..1f065bbf69b 100644 --- a/dbms/src/Interpreters/InterpreterFactory.h +++ b/dbms/src/Interpreters/InterpreterFactory.h @@ -2,14 +2,13 @@ #include #include +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; class InterpreterFactory diff --git a/dbms/src/Interpreters/InterpreterKillQueryQuery.h b/dbms/src/Interpreters/InterpreterKillQueryQuery.h index 9294e45eab8..fab4b304865 100644 --- a/dbms/src/Interpreters/InterpreterKillQueryQuery.h +++ b/dbms/src/Interpreters/InterpreterKillQueryQuery.h @@ -1,14 +1,13 @@ #pragma once #include +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; class InterpreterKillQueryQuery : public IInterpreter @@ -28,4 +27,3 @@ private: } - diff --git a/dbms/src/Interpreters/InterpreterOptimizeQuery.h b/dbms/src/Interpreters/InterpreterOptimizeQuery.h index 03c369b0e4a..251d8ea02f3 100644 --- a/dbms/src/Interpreters/InterpreterOptimizeQuery.h +++ b/dbms/src/Interpreters/InterpreterOptimizeQuery.h @@ -1,14 +1,13 @@ #pragma once #include +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; /** Just call method "optimize" for table. diff --git a/dbms/src/Interpreters/InterpreterRenameQuery.h b/dbms/src/Interpreters/InterpreterRenameQuery.h index e9a36277ef0..0433c638468 100644 --- a/dbms/src/Interpreters/InterpreterRenameQuery.h +++ b/dbms/src/Interpreters/InterpreterRenameQuery.h @@ -1,14 +1,13 @@ #pragma once #include +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; /** Rename one table diff --git a/dbms/src/Interpreters/InterpreterSelectQuery.cpp b/dbms/src/Interpreters/InterpreterSelectQuery.cpp index 44b8f85a932..70c25619889 100644 --- a/dbms/src/Interpreters/InterpreterSelectQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSelectQuery.cpp @@ -1078,7 +1078,8 @@ void InterpreterSelectQuery::executeFetchColumns( void InterpreterSelectQuery::executeWhere(Pipeline & pipeline, const ExpressionActionsPtr & expression, bool remove_fiter) { - pipeline.transform([&](auto & stream) { + pipeline.transform([&](auto & stream) + { stream = std::make_shared( stream, expression, query_ptr->as()->where_expression->getColumnName(), remove_fiter); }); @@ -1206,7 +1207,8 @@ void InterpreterSelectQuery::executeMergeAggregated(Pipeline & pipeline, bool ov void InterpreterSelectQuery::executeHaving(Pipeline & pipeline, const ExpressionActionsPtr & expression) { - pipeline.transform([&](auto & stream) { + pipeline.transform([&](auto & stream) + { stream = std::make_shared( stream, expression, query_ptr->as()->having_expression->getColumnName()); }); diff --git a/dbms/src/Interpreters/InterpreterSetQuery.h b/dbms/src/Interpreters/InterpreterSetQuery.h index 7dbd444f6f1..434765cf7d0 100644 --- a/dbms/src/Interpreters/InterpreterSetQuery.h +++ b/dbms/src/Interpreters/InterpreterSetQuery.h @@ -1,15 +1,14 @@ #pragma once #include +#include namespace DB { class Context; -class IAST; class ASTSetQuery; -using ASTPtr = std::shared_ptr; /** Change one or several settings for the session or just for the current context. diff --git a/dbms/src/Interpreters/InterpreterShowCreateQuery.h b/dbms/src/Interpreters/InterpreterShowCreateQuery.h index 5e8672c1767..5ac98509b23 100644 --- a/dbms/src/Interpreters/InterpreterShowCreateQuery.h +++ b/dbms/src/Interpreters/InterpreterShowCreateQuery.h @@ -1,14 +1,13 @@ #pragma once #include +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; /** Return single row with single column "statement" of type String with text of query to CREATE specified table. diff --git a/dbms/src/Interpreters/InterpreterShowProcesslistQuery.h b/dbms/src/Interpreters/InterpreterShowProcesslistQuery.h index ee180e76699..6b87fd7edc3 100644 --- a/dbms/src/Interpreters/InterpreterShowProcesslistQuery.h +++ b/dbms/src/Interpreters/InterpreterShowProcesslistQuery.h @@ -1,14 +1,13 @@ #pragma once #include +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; /** Return list of currently executing queries. diff --git a/dbms/src/Interpreters/InterpreterShowTablesQuery.h b/dbms/src/Interpreters/InterpreterShowTablesQuery.h index 3f661da3e2d..fc5cb2b7505 100644 --- a/dbms/src/Interpreters/InterpreterShowTablesQuery.h +++ b/dbms/src/Interpreters/InterpreterShowTablesQuery.h @@ -1,14 +1,13 @@ #pragma once #include +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; /** Return a list of tables or databases meets specified conditions. diff --git a/dbms/src/Interpreters/InterpreterSystemQuery.h b/dbms/src/Interpreters/InterpreterSystemQuery.h index fb92e799761..65aaf789419 100644 --- a/dbms/src/Interpreters/InterpreterSystemQuery.h +++ b/dbms/src/Interpreters/InterpreterSystemQuery.h @@ -1,15 +1,15 @@ #pragma once + #include +#include namespace DB { class Context; -class IAST; class ASTSystemQuery; class IStorage; -using ASTPtr = std::shared_ptr; using StoragePtr = std::shared_ptr; diff --git a/dbms/src/Interpreters/InterpreterUseQuery.h b/dbms/src/Interpreters/InterpreterUseQuery.h index 988ccb741fa..ae409117afd 100644 --- a/dbms/src/Interpreters/InterpreterUseQuery.h +++ b/dbms/src/Interpreters/InterpreterUseQuery.h @@ -1,14 +1,13 @@ #pragma once #include +#include namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; /** Change default database for session. diff --git a/dbms/src/Storages/StorageMaterializedView.h b/dbms/src/Storages/StorageMaterializedView.h index 8c2657b484b..665f6243a32 100644 --- a/dbms/src/Storages/StorageMaterializedView.h +++ b/dbms/src/Storages/StorageMaterializedView.h @@ -2,16 +2,13 @@ #include +#include #include namespace DB { -class IAST; // XXX: should include full class - for proper use inside inline methods -using ASTPtr = std::shared_ptr; - - class StorageMaterializedView : public ext::shared_ptr_helper, public IStorage { public: diff --git a/dbms/src/Storages/StorageView.h b/dbms/src/Storages/StorageView.h index fed6664b8eb..afd9b5ce326 100644 --- a/dbms/src/Storages/StorageView.h +++ b/dbms/src/Storages/StorageView.h @@ -1,17 +1,15 @@ #pragma once -#include -#include #include +#include +#include + +#include namespace DB { -class IAST; -using ASTPtr = std::shared_ptr; - - class StorageView : public ext::shared_ptr_helper, public IStorage { public: diff --git a/dbms/src/TableFunctions/ITableFunction.h b/dbms/src/TableFunctions/ITableFunction.h index ddf900fa65c..39ef7857a3a 100644 --- a/dbms/src/TableFunctions/ITableFunction.h +++ b/dbms/src/TableFunctions/ITableFunction.h @@ -1,14 +1,15 @@ #pragma once +#include + #include #include + namespace DB { class Context; -class IAST; -using ASTPtr = std::shared_ptr; class IStorage; using StoragePtr = std::shared_ptr; From 67eefa7b12622d63bee64ab0d1c200d89dd9b30b Mon Sep 17 00:00:00 2001 From: Ivan Lezhankin Date: Tue, 12 Mar 2019 15:41:57 +0300 Subject: [PATCH 05/11] Revert wrong replacements of dynamic_cast. dynamic_cast to intermediate type is not equivalent to typeid_cast --- dbms/programs/client/Client.cpp | 3 ++- dbms/programs/copier/ClusterCopier.cpp | 2 +- dbms/src/Common/typeid_cast.h | 15 +++++++++++---- .../Interpreters/InterpreterShowCreateQuery.cpp | 3 ++- dbms/src/Interpreters/SyntaxAnalyzer.cpp | 5 ++--- dbms/src/Interpreters/executeQuery.cpp | 3 ++- dbms/src/Parsers/ASTQueryWithOutput.cpp | 3 ++- dbms/src/Parsers/ExpressionElementParsers.cpp | 3 ++- dbms/src/Parsers/IAST.h | 2 ++ dbms/src/Parsers/ParserQueryWithOutput.cpp | 3 ++- 10 files changed, 28 insertions(+), 14 deletions(-) diff --git a/dbms/programs/client/Client.cpp b/dbms/programs/client/Client.cpp index 8acb7ae6709..73ad25fca8e 100644 --- a/dbms/programs/client/Client.cpp +++ b/dbms/programs/client/Client.cpp @@ -1228,7 +1228,8 @@ private: String current_format = format; /// The query can specify output format or output file. - if (const auto * query_with_output = parsed_query->as()) + /// FIXME: try to prettify this cast using `as<>()` + if (const auto * query_with_output = dynamic_cast(parsed_query.get())) { if (query_with_output->out_file) { diff --git a/dbms/programs/copier/ClusterCopier.cpp b/dbms/programs/copier/ClusterCopier.cpp index 79b13a03850..bcbf8771487 100644 --- a/dbms/programs/copier/ClusterCopier.cpp +++ b/dbms/programs/copier/ClusterCopier.cpp @@ -501,7 +501,7 @@ static ASTPtr extractPartitionKey(const ASTPtr & storage_ast) } ASTPtr arguments_ast = engine->arguments->clone(); - ASTs & arguments = arguments_ast->as()->children; // FIXME: what' the point of casting? + ASTs & arguments = arguments_ast->children; if (isExtendedDefinitionStorage(storage_ast)) { diff --git a/dbms/src/Common/typeid_cast.h b/dbms/src/Common/typeid_cast.h index 99faeb40742..11b083d21d9 100644 --- a/dbms/src/Common/typeid_cast.h +++ b/dbms/src/Common/typeid_cast.h @@ -35,8 +35,15 @@ std::enable_if_t, To> typeid_cast(From & from) template To typeid_cast(From * from) { - if (typeid(*from) == typeid(std::remove_pointer_t)) - return static_cast(from); - else - return nullptr; + try + { + if (typeid(*from) == typeid(std::remove_pointer_t)) + return static_cast(from); + else + return nullptr; + } + catch (const std::exception & e) + { + throw DB::Exception(e.what(), DB::ErrorCodes::BAD_CAST); + } } diff --git a/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp b/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp index 625ca671a69..8be3b90ba9e 100644 --- a/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp +++ b/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp @@ -42,7 +42,8 @@ Block InterpreterShowCreateQuery::getSampleBlock() BlockInputStreamPtr InterpreterShowCreateQuery::executeImpl() { - const auto * ast = query_ptr->as(); + /// FIXME: try to prettify this cast using `as<>()` + const auto * ast = dynamic_cast(query_ptr.get()); if (ast->temporary && !ast->database.empty()) throw Exception("Temporary databases are not possible.", ErrorCodes::SYNTAX_ERROR); diff --git a/dbms/src/Interpreters/SyntaxAnalyzer.cpp b/dbms/src/Interpreters/SyntaxAnalyzer.cpp index d87be9b7bd0..0586f7f04c9 100644 --- a/dbms/src/Interpreters/SyntaxAnalyzer.cpp +++ b/dbms/src/Interpreters/SyntaxAnalyzer.cpp @@ -359,11 +359,10 @@ void optimizeLimitBy(const ASTSelectQuery * select_query) /// Remove duplicated columns from USING(...). void optimizeUsing(const ASTSelectQuery * select_query) { - const auto * node = select_query->join()->as(); - if (!node) + if (!select_query->join()) return; - const auto * table_join = node->table_join->as(); + const auto * table_join = select_query->join()->table_join->as(); if (!(table_join && table_join->using_expression_list)) return; diff --git a/dbms/src/Interpreters/executeQuery.cpp b/dbms/src/Interpreters/executeQuery.cpp index 87badd74ba4..4358960d7b8 100644 --- a/dbms/src/Interpreters/executeQuery.cpp +++ b/dbms/src/Interpreters/executeQuery.cpp @@ -506,7 +506,8 @@ void executeQuery( if (streams.in) { - const auto * ast_query_with_output = ast->as(); + /// FIXME: try to prettify this cast using `as<>()` + const auto * ast_query_with_output = dynamic_cast(ast.get()); WriteBuffer * out_buf = &ostr; std::optional out_file_buf; diff --git a/dbms/src/Parsers/ASTQueryWithOutput.cpp b/dbms/src/Parsers/ASTQueryWithOutput.cpp index 1c67d20be22..95bcaaad416 100644 --- a/dbms/src/Parsers/ASTQueryWithOutput.cpp +++ b/dbms/src/Parsers/ASTQueryWithOutput.cpp @@ -49,7 +49,8 @@ void ASTQueryWithOutput::formatImpl(const FormatSettings & s, FormatState & stat bool ASTQueryWithOutput::resetOutputASTIfExist(IAST & ast) { - if (auto * ast_with_output = ast.as()) + /// FIXME: try to prettify this cast using `as<>()` + if (auto * ast_with_output = dynamic_cast(&ast)) { ast_with_output->format.reset(); ast_with_output->out_file.reset(); diff --git a/dbms/src/Parsers/ExpressionElementParsers.cpp b/dbms/src/Parsers/ExpressionElementParsers.cpp index 4f19469c756..9df7c0a05a4 100644 --- a/dbms/src/Parsers/ExpressionElementParsers.cpp +++ b/dbms/src/Parsers/ExpressionElementParsers.cpp @@ -1254,7 +1254,8 @@ bool ParserWithOptionalAlias::parseImpl(Pos & pos, ASTPtr & node, Expected & exp ASTPtr alias_node; if (ParserAlias(allow_alias_without_as_keyword_now).parse(pos, alias_node, expected)) { - if (auto * ast_with_alias = node->as()) + /// FIXME: try to prettify this cast using `as<>()` + if (auto * ast_with_alias = dynamic_cast(node.get())) { getIdentifierName(alias_node, ast_with_alias->alias); ast_with_alias->prefer_alias_to_column_name = prefer_alias_to_column_name; diff --git a/dbms/src/Parsers/IAST.h b/dbms/src/Parsers/IAST.h index 294d7453c41..18092593634 100644 --- a/dbms/src/Parsers/IAST.h +++ b/dbms/src/Parsers/IAST.h @@ -45,12 +45,14 @@ public: template Derived * as() { + // TODO: check, if we downcasting to base type, then just return |this|. return typeid_cast(this); } template const Derived * as() const { + // TODO: check, if we downcasting to base type, then just return |this|. return typeid_cast(this); } diff --git a/dbms/src/Parsers/ParserQueryWithOutput.cpp b/dbms/src/Parsers/ParserQueryWithOutput.cpp index 1b38cee3ba5..0ee67dab9c9 100644 --- a/dbms/src/Parsers/ParserQueryWithOutput.cpp +++ b/dbms/src/Parsers/ParserQueryWithOutput.cpp @@ -62,7 +62,8 @@ bool ParserQueryWithOutput::parseImpl(Pos & pos, ASTPtr & node, Expected & expec if (!parsed) return false; - auto * query_with_output = query->as(); + /// FIXME: try to prettify this cast using `as<>()` + auto * query_with_output = dynamic_cast(query.get()); ParserKeyword s_into_outfile("INTO OUTFILE"); if (s_into_outfile.ignore(pos, expected)) From 39f7225bd401536068f338bddb6d57a8741fa292 Mon Sep 17 00:00:00 2001 From: Ivan Lezhankin Date: Tue, 12 Mar 2019 17:07:02 +0300 Subject: [PATCH 06/11] Fix build after merge --- .../Interpreters/InterpreterSelectQuery.cpp | 151 ++++++++---------- .../src/Interpreters/InterpreterSelectQuery.h | 13 +- 2 files changed, 75 insertions(+), 89 deletions(-) diff --git a/dbms/src/Interpreters/InterpreterSelectQuery.cpp b/dbms/src/Interpreters/InterpreterSelectQuery.cpp index acb0d09e75d..dc239a22d32 100644 --- a/dbms/src/Interpreters/InterpreterSelectQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSelectQuery.cpp @@ -23,7 +23,6 @@ #include #include -#include #include #include #include @@ -169,9 +168,9 @@ InterpreterSelectQuery::InterpreterSelectQuery( } max_streams = settings.max_threads; - ASTSelectQuery & query = selectQuery(); + auto & query = getSelectQuery(); - ASTPtr table_expression = extractTableExpression(*query_ptr->as(), 0); + ASTPtr table_expression = extractTableExpression(query, 0); bool is_table_func = false; bool is_subquery = false; @@ -224,15 +223,13 @@ InterpreterSelectQuery::InterpreterSelectQuery( if (!only_analyze) { - const auto * query = query_ptr->as(); - - if (query->sample_size() && (input || !storage || !storage->supportsSampling())) + if (query.sample_size() && (input || !storage || !storage->supportsSampling())) throw Exception("Illegal SAMPLE: table doesn't support sampling", ErrorCodes::SAMPLING_NOT_SUPPORTED); - if (query->final() && (input || !storage || !storage->supportsFinal())) + if (query.final() && (input || !storage || !storage->supportsFinal())) throw Exception((!input && storage) ? "Storage " + storage->getName() + " doesn't support FINAL" : "Illegal FINAL", ErrorCodes::ILLEGAL_FINAL); - if (query->prewhere_expression && (input || !storage || !storage->supportsPrewhere())) + if (query.prewhere_expression && (input || !storage || !storage->supportsPrewhere())) throw Exception((!input && storage) ? "Storage " + storage->getName() + " doesn't support PREWHERE" : "Illegal PREWHERE", ErrorCodes::ILLEGAL_PREWHERE); /// Save the new temporary tables in the query context @@ -279,15 +276,9 @@ InterpreterSelectQuery::InterpreterSelectQuery( } -ASTSelectQuery & InterpreterSelectQuery::selectQuery() -{ - return *query_ptr->as(); -} - - void InterpreterSelectQuery::getDatabaseAndTableNames(String & database_name, String & table_name) { - if (auto db_and_table = getDatabaseAndTable(selectQuery(), 0)) + if (auto db_and_table = getDatabaseAndTable(getSelectQuery(), 0)) { table_name = db_and_table->table; database_name = db_and_table->database; @@ -386,19 +377,18 @@ InterpreterSelectQuery::AnalysisResult InterpreterSelectQuery::analyzeExpression { ExpressionActionsChain chain(context); - ASTSelectQuery & query = selectQuery(); + auto & query = getSelectQuery(); Names additional_required_columns_after_prewhere; - const auto * query = query_ptr->as(); - if (storage && query->sample_size()) + if (storage && query.sample_size()) { Names columns_for_sampling = storage->getColumnsRequiredForSampling(); additional_required_columns_after_prewhere.insert(additional_required_columns_after_prewhere.end(), columns_for_sampling.begin(), columns_for_sampling.end()); } - if (storage && query->final()) + if (storage && query.final()) { Names columns_for_final = storage->getColumnsRequiredForFinal(); additional_required_columns_after_prewhere.insert(additional_required_columns_after_prewhere.end(), @@ -410,7 +400,7 @@ InterpreterSelectQuery::AnalysisResult InterpreterSelectQuery::analyzeExpression has_prewhere = true; res.prewhere_info = std::make_shared( - chain.steps.front().actions, query->prewhere_expression->getColumnName()); + chain.steps.front().actions, query.prewhere_expression->getColumnName()); chain.addStep(); } @@ -511,7 +501,8 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt * then perform the remaining operations with one resulting stream. */ - ASTSelectQuery & query = selectQuery(); + /// Now we will compose block streams that perform the necessary actions. + auto & query = getSelectQuery(); const Settings & settings = context.getSettingsRef(); QueryProcessingStage::Enum from_stage = QueryProcessingStage::FetchColumns; @@ -531,10 +522,8 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt query_info.syntax_analyzer_result = syntax_analyzer_result; query_info.sets = query_analyzer->getPreparedSets(); - const auto * query = query_ptr->as(); - /// Try transferring some condition from WHERE to PREWHERE if enabled and viable - if (settings.optimize_move_to_prewhere && query->where_expression && !query->prewhere_expression && !query->final()) + if (settings.optimize_move_to_prewhere && query.where_expression && !query.prewhere_expression && !query.final()) MergeTreeWhereOptimizer{query_info, context, merge_tree.getData(), query_analyzer->getRequiredSourceColumns(), log}; }; @@ -575,13 +564,10 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt if (to_stage > QueryProcessingStage::FetchColumns) { - /// Now we will compose block streams that perform the necessary actions. - const auto * query = query_ptr->as(); - /// Do I need to aggregate in a separate row rows that have not passed max_rows_to_group_by. bool aggregate_overflow_row = expressions.need_aggregate && - query->group_by_with_totals && + query.group_by_with_totals && settings.max_rows_to_group_by && settings.group_by_overflow_mode == OverflowMode::ANY && settings.totals_mode != TotalsMode::AFTER_HAVING_EXCLUSIVE; @@ -590,13 +576,13 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt bool aggregate_final = expressions.need_aggregate && to_stage > QueryProcessingStage::WithMergeableState && - !query->group_by_with_totals && !query->group_by_with_rollup && !query->group_by_with_cube; + !query.group_by_with_totals && !query.group_by_with_rollup && !query.group_by_with_cube; if (expressions.first_stage) { if (expressions.hasJoin()) { - const auto * join = query->join()->table_join->as(); + const auto * join = query.join()->table_join->as(); if (isRightOrFull(join->kind)) pipeline.stream_with_non_joined_data = expressions.before_join->createStreamWithNonJoinedDataIfFullOrRightJoin( pipeline.firstStream()->getHeader(), settings.max_block_size); @@ -626,10 +612,10 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt if (expressions.has_order_by) executeOrder(pipeline); - if (expressions.has_order_by && query->limit_length) + if (expressions.has_order_by && query.limit_length) executeDistinct(pipeline, false, expressions.selected_columns); - if (query->limit_length) + if (query.limit_length) executePreLimit(pipeline); } @@ -651,20 +637,20 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt if (!aggregate_final) { - if (query->group_by_with_totals) + if (query.group_by_with_totals) { - bool final = !query->group_by_with_rollup && !query->group_by_with_cube; + bool final = !query.group_by_with_rollup && !query.group_by_with_cube; executeTotalsAndHaving(pipeline, expressions.has_having, expressions.before_having, aggregate_overflow_row, final); } - if (query->group_by_with_rollup) + if (query.group_by_with_rollup) executeRollupOrCube(pipeline, Modificator::ROLLUP); - else if (query->group_by_with_cube) + else if (query.group_by_with_cube) executeRollupOrCube(pipeline, Modificator::CUBE); - if ((query->group_by_with_rollup || query->group_by_with_cube) && expressions.has_having) + if ((query.group_by_with_rollup || query.group_by_with_cube) && expressions.has_having) { - if (query->group_by_with_totals) + if (query.group_by_with_totals) throw Exception("WITH TOTALS and WITH ROLLUP or CUBE are not supported together in presence of HAVING", ErrorCodes::NOT_IMPLEMENTED); executeHaving(pipeline, expressions.before_having); } @@ -675,28 +661,28 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt executeExpression(pipeline, expressions.before_order_and_select); executeDistinct(pipeline, true, expressions.selected_columns); - need_second_distinct_pass = query->distinct && pipeline.hasMoreThanOneStream(); + need_second_distinct_pass = query.distinct && pipeline.hasMoreThanOneStream(); } else { - need_second_distinct_pass = query->distinct && pipeline.hasMoreThanOneStream(); + need_second_distinct_pass = query.distinct && pipeline.hasMoreThanOneStream(); - if (query->group_by_with_totals && !aggregate_final) + if (query.group_by_with_totals && !aggregate_final) { - bool final = !query->group_by_with_rollup && !query->group_by_with_cube; + bool final = !query.group_by_with_rollup && !query.group_by_with_cube; executeTotalsAndHaving(pipeline, expressions.has_having, expressions.before_having, aggregate_overflow_row, final); } - if ((query->group_by_with_rollup || query->group_by_with_cube) && !aggregate_final) + if ((query.group_by_with_rollup || query.group_by_with_cube) && !aggregate_final) { - if (query->group_by_with_rollup) + if (query.group_by_with_rollup) executeRollupOrCube(pipeline, Modificator::ROLLUP); - else if (query->group_by_with_cube) + else if (query.group_by_with_cube) executeRollupOrCube(pipeline, Modificator::CUBE); if (expressions.has_having) { - if (query->group_by_with_totals) + if (query.group_by_with_totals) throw Exception("WITH TOTALS and WITH ROLLUP or CUBE are not supported together in presence of HAVING", ErrorCodes::NOT_IMPLEMENTED); executeHaving(pipeline, expressions.before_having); } @@ -709,7 +695,7 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt * but there is no aggregation, then on the remote servers ORDER BY was made * - therefore, we merge the sorted streams from remote servers. */ - if (!expressions.first_stage && !expressions.need_aggregate && !(query->group_by_with_totals && !aggregate_final)) + if (!expressions.first_stage && !expressions.need_aggregate && !(query.group_by_with_totals && !aggregate_final)) executeMergeSorted(pipeline); else /// Otherwise, just sort. executeOrder(pipeline); @@ -718,14 +704,14 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt /** Optimization - if there are several sources and there is LIMIT, then first apply the preliminary LIMIT, * limiting the number of rows in each up to `offset + limit`. */ - if (query->limit_length && pipeline.hasMoreThanOneStream() && !query->distinct && !expressions.has_limit_by && !settings.extremes) + if (query.limit_length && pipeline.hasMoreThanOneStream() && !query.distinct && !expressions.has_limit_by && !settings.extremes) { executePreLimit(pipeline); } if (need_second_distinct_pass - || query->limit_length - || query->limit_by_expression_list + || query.limit_length + || query.limit_by_expression_list || pipeline.stream_with_non_joined_data) { need_merge_streams = true; @@ -808,7 +794,7 @@ void InterpreterSelectQuery::executeFetchColumns( QueryProcessingStage::Enum processing_stage, Pipeline & pipeline, const PrewhereInfoPtr & prewhere_info, const Names & columns_to_remove_after_prewhere) { - ASTSelectQuery & query = selectQuery(); + auto & query = getSelectQuery(); const Settings & settings = context.getSettingsRef(); /// Actions to calculate ALIAS if required. @@ -967,22 +953,21 @@ void InterpreterSelectQuery::executeFetchColumns( } UInt64 max_block_size = settings.max_block_size; - const auto * query = query_ptr->as(); - auto [limit_length, limit_offset] = getLimitLengthAndOffset(*query, context); + auto [limit_length, limit_offset] = getLimitLengthAndOffset(query, context); /** Optimization - if not specified DISTINCT, WHERE, GROUP, HAVING, ORDER, LIMIT BY but LIMIT is specified, and limit + offset < max_block_size, * then as the block size we will use limit + offset (not to read more from the table than requested), * and also set the number of threads to 1. */ - if (!query->distinct - && !query->prewhere_expression - && !query->where_expression - && !query->group_expression_list - && !query->having_expression - && !query->order_expression_list - && !query->limit_by_expression_list - && query->limit_length + if (!query.distinct + && !query.prewhere_expression + && !query.where_expression + && !query.group_expression_list + && !query.having_expression + && !query.order_expression_list + && !query.limit_by_expression_list + && query.limit_length && !query_analyzer->hasAggregation() && limit_length + limit_offset < max_block_size) { @@ -1004,7 +989,7 @@ void InterpreterSelectQuery::executeFetchColumns( /// If we need less number of columns that subquery have - update the interpreter. if (required_columns.size() < source_header.columns()) { - ASTPtr subquery = extractTableExpression(*query, 0); + ASTPtr subquery = extractTableExpression(query, 0); if (!subquery) throw Exception("Subquery expected", ErrorCodes::LOGICAL_ERROR); @@ -1104,7 +1089,7 @@ void InterpreterSelectQuery::executeWhere(Pipeline & pipeline, const ExpressionA { pipeline.transform([&](auto & stream) { - stream = std::make_shared(stream, expression, selectQuery().where_expression->getColumnName(), remove_fiter); + stream = std::make_shared(stream, expression, getSelectQuery().where_expression->getColumnName(), remove_fiter); }); } @@ -1232,7 +1217,7 @@ void InterpreterSelectQuery::executeHaving(Pipeline & pipeline, const Expression { pipeline.transform([&](auto & stream) { - stream = std::make_shared(stream, expression, selectQuery().having_expression->getColumnName()); + stream = std::make_shared(stream, expression, getSelectQuery().having_expression->getColumnName()); }); } @@ -1247,7 +1232,7 @@ void InterpreterSelectQuery::executeTotalsAndHaving(Pipeline & pipeline, bool ha pipeline.firstStream(), overflow_row, expression, - has_having ? selectQuery().having_expression->getColumnName() : "", + has_having ? getSelectQuery().having_expression->getColumnName() : "", settings.totals_mode, settings.totals_auto_threshold, final); @@ -1315,7 +1300,7 @@ static SortDescription getSortDescription(const ASTSelectQuery & query) void InterpreterSelectQuery::executeOrder(Pipeline & pipeline) { - ASTSelectQuery & query = selectQuery(); + auto & query = getSelectQuery(); SortDescription order_descr = getSortDescription(query); UInt64 limit = getLimitForSorting(query, context); @@ -1347,7 +1332,7 @@ void InterpreterSelectQuery::executeOrder(Pipeline & pipeline) void InterpreterSelectQuery::executeMergeSorted(Pipeline & pipeline) { - ASTSelectQuery & query = selectQuery(); + auto & query = getSelectQuery(); SortDescription order_descr = getSortDescription(query); UInt64 limit = getLimitForSorting(query, context); @@ -1384,16 +1369,16 @@ void InterpreterSelectQuery::executeProjection(Pipeline & pipeline, const Expres void InterpreterSelectQuery::executeDistinct(Pipeline & pipeline, bool before_order, Names columns) { - ASTSelectQuery & query = selectQuery(); + auto & query = getSelectQuery(); if (query.distinct) { const Settings & settings = context.getSettingsRef(); - auto [limit_length, limit_offset] = getLimitLengthAndOffset(*query, context); + auto [limit_length, limit_offset] = getLimitLengthAndOffset(query, context); UInt64 limit_for_distinct = 0; /// If after this stage of DISTINCT ORDER BY is not executed, then you can get no more than limit_length + limit_offset of different rows. - if (!query->order_expression_list || !before_order) + if (!query.order_expression_list || !before_order) limit_for_distinct = limit_length + limit_offset; pipeline.transform([&](auto & stream) @@ -1427,11 +1412,11 @@ void InterpreterSelectQuery::executeUnion(Pipeline & pipeline) /// Preliminary LIMIT - is used in every source, if there are several sources, before they are combined. void InterpreterSelectQuery::executePreLimit(Pipeline & pipeline) { - ASTSelectQuery & query = selectQuery(); + auto & query = getSelectQuery(); /// If there is LIMIT - if (query->limit_length) + if (query.limit_length) { - auto [limit_length, limit_offset] = getLimitLengthAndOffset(*query, context); + auto [limit_length, limit_offset] = getLimitLengthAndOffset(query, context); pipeline.transform([&, limit = limit_length + limit_offset](auto & stream) { stream = std::make_shared(stream, limit, 0, false); @@ -1442,15 +1427,15 @@ void InterpreterSelectQuery::executePreLimit(Pipeline & pipeline) void InterpreterSelectQuery::executeLimitBy(Pipeline & pipeline) { - ASTSelectQuery & query = selectQuery(); + auto & query = getSelectQuery(); if (!query.limit_by_value || !query.limit_by_expression_list) return; Names columns; - for (const auto & elem : query->limit_by_expression_list->children) + for (const auto & elem : query.limit_by_expression_list->children) columns.emplace_back(elem->getColumnName()); - UInt64 value = getLimitUIntValue(query->limit_by_value, context); + UInt64 value = getLimitUIntValue(query.limit_by_value, context); pipeline.transform([&](auto & stream) { @@ -1484,9 +1469,9 @@ bool hasWithTotalsInAnySubqueryInFromClause(const ASTSelectQuery & query) void InterpreterSelectQuery::executeLimit(Pipeline & pipeline) { - ASTSelectQuery & query = selectQuery(); + auto & query = getSelectQuery(); /// If there is LIMIT - if (query->limit_length) + if (query.limit_length) { /** Rare case: * if there is no WITH TOTALS and there is a subquery in FROM, and there is WITH TOTALS on one of the levels, @@ -1499,15 +1484,15 @@ void InterpreterSelectQuery::executeLimit(Pipeline & pipeline) */ bool always_read_till_end = false; - if (query->group_by_with_totals && !query->order_expression_list) + if (query.group_by_with_totals && !query.order_expression_list) always_read_till_end = true; - if (!query->group_by_with_totals && hasWithTotalsInAnySubqueryInFromClause(*query)) + if (!query.group_by_with_totals && hasWithTotalsInAnySubqueryInFromClause(query)) always_read_till_end = true; UInt64 limit_length; UInt64 limit_offset; - std::tie(limit_length, limit_offset) = getLimitLengthAndOffset(*query, context); + std::tie(limit_length, limit_offset) = getLimitLengthAndOffset(query, context); pipeline.transform([&](auto & stream) { @@ -1556,13 +1541,13 @@ void InterpreterSelectQuery::unifyStreams(Pipeline & pipeline) void InterpreterSelectQuery::ignoreWithTotals() { - selectQuery().group_by_with_totals = false; + getSelectQuery().group_by_with_totals = false; } void InterpreterSelectQuery::initSettings() { - ASTSelectQuery & query = selectQuery(); + auto & query = getSelectQuery(); if (query.settings) InterpreterSetQuery(query.settings, context).executeForCurrentContext(); } diff --git a/dbms/src/Interpreters/InterpreterSelectQuery.h b/dbms/src/Interpreters/InterpreterSelectQuery.h index 89fdc35eb7b..03e13ba8eac 100644 --- a/dbms/src/Interpreters/InterpreterSelectQuery.h +++ b/dbms/src/Interpreters/InterpreterSelectQuery.h @@ -3,11 +3,12 @@ #include #include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include #include @@ -16,7 +17,6 @@ namespace Poco { class Logger; } namespace DB { -class ASTSelectQuery; struct SubqueryForSet; class InterpreterSelectWithUnionQuery; @@ -99,6 +99,8 @@ private: bool only_analyze_, bool modify_inplace); + ASTSelectQuery & getSelectQuery() { return *query_ptr->as(); } + struct Pipeline { @@ -133,7 +135,6 @@ private: } }; - ASTSelectQuery & selectQuery(); void executeImpl(Pipeline & pipeline, const BlockInputStreamPtr & prepared_input, bool dry_run); From 0dd31b587ed6429f3dd4cacdcd3659b4945d40f6 Mon Sep 17 00:00:00 2001 From: Ivan Lezhankin Date: Wed, 13 Mar 2019 14:53:31 +0300 Subject: [PATCH 07/11] Fix typo --- dbms/src/Storages/StorageHDFS.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dbms/src/Storages/StorageHDFS.cpp b/dbms/src/Storages/StorageHDFS.cpp index b7607112acb..4222fcf4dd8 100644 --- a/dbms/src/Storages/StorageHDFS.cpp +++ b/dbms/src/Storages/StorageHDFS.cpp @@ -167,7 +167,7 @@ void registerStorageHDFS(StorageFactory & factory) engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); - String format_name = engine_args[0]->as()->value.safeGet(); + String format_name = engine_args[1]->as()->value.safeGet(); return StorageHDFS::create(url, args.table_name, format_name, args.columns, args.context); }); From 61c24e084420a29e37903889718a96b91a327d22 Mon Sep 17 00:00:00 2001 From: Ivan Lezhankin Date: Fri, 15 Mar 2019 16:12:11 +0300 Subject: [PATCH 08/11] Overload template method |as<>()| with reference type. Move promotion logic to a separate class --- dbms/programs/client/Client.cpp | 24 +++++++-------- dbms/src/Common/TypePromotion.h | 54 +++++++++++++++++++++++++++++++++ dbms/src/Parsers/IAST.h | 18 ++--------- 3 files changed, 68 insertions(+), 28 deletions(-) create mode 100644 dbms/src/Common/TypePromotion.h diff --git a/dbms/programs/client/Client.cpp b/dbms/programs/client/Client.cpp index 73ad25fca8e..724bbc9eb93 100644 --- a/dbms/programs/client/Client.cpp +++ b/dbms/programs/client/Client.cpp @@ -880,12 +880,12 @@ private: void processInsertQuery() { /// Send part of query without data, because data will be sent separately. - const auto * insert_query = parsed_query->as(); - String query_without_data = insert_query->data - ? query.substr(0, insert_query->data - query.data()) + const auto & parsed_insert_query = parsed_query->as(); + String query_without_data = parsed_insert_query.data + ? query.substr(0, parsed_insert_query.data - query.data()) : query; - if (!insert_query->data && (is_interactive || (stdin_is_not_tty && std_in.eof()))) + if (!parsed_insert_query.data && (is_interactive || (stdin_is_not_tty && std_in.eof()))) throw Exception("No data to insert", ErrorCodes::NO_DATA_TO_INSERT); connection->sendQuery(query_without_data, query_id, QueryProcessingStage::Complete, &context.getSettingsRef(), nullptr, true); @@ -937,14 +937,14 @@ private: void sendData(Block & sample, const ColumnsDescription & columns_description) { /// If INSERT data must be sent. - const auto * insert_query = parsed_query->as(); - if (!insert_query) + const auto * parsed_insert_query = parsed_query->as(); + if (!parsed_insert_query) return; - if (insert_query->data) + if (parsed_insert_query->data) { /// Send data contained in the query. - ReadBufferFromMemory data_in(insert_query->data, insert_query->end - insert_query->data); + ReadBufferFromMemory data_in(parsed_insert_query->data, parsed_insert_query->end - parsed_insert_query->data); sendDataFrom(data_in, sample, columns_description); } else if (!is_interactive) @@ -1233,8 +1233,8 @@ private: { if (query_with_output->out_file) { - const auto * out_file_node = query_with_output->out_file->as(); - const auto & out_file = out_file_node->value.safeGet(); + const auto & out_file_node = query_with_output->out_file->as(); + const auto & out_file = out_file_node.value.safeGet(); out_file_buf.emplace(out_file, DBMS_DEFAULT_BUFFER_SIZE, O_WRONLY | O_EXCL | O_CREAT); out_buf = &*out_file_buf; @@ -1247,8 +1247,8 @@ private: { if (has_vertical_output_suffix) throw Exception("Output format already specified", ErrorCodes::CLIENT_OUTPUT_FORMAT_SPECIFIED); - const auto * id = query_with_output->format->as(); - current_format = id->name; + const auto & id = query_with_output->format->as(); + current_format = id.name; } if (query_with_output->settings_ast) { diff --git a/dbms/src/Common/TypePromotion.h b/dbms/src/Common/TypePromotion.h new file mode 100644 index 00000000000..e338f3b9fca --- /dev/null +++ b/dbms/src/Common/TypePromotion.h @@ -0,0 +1,54 @@ +#pragma once + +#include + +namespace DB { + +template +class TypePromotion { +private: + /// Need a helper-struct to fight the lack of the function-template partial specialization. + template , bool is_const = std::is_const_v> + struct CastHelper; + + template + struct CastHelper + { + auto & value(Base * ptr) { return typeid_cast(*ptr); } + }; + + template + struct CastHelper + { + auto & value(const Base * ptr) { return typeid_cast(*ptr); } + }; + + template + struct CastHelper + { + auto * value(Base * ptr) { return typeid_cast(ptr); } + }; + + template + struct CastHelper + { + auto * value(const Base * ptr) { return typeid_cast(ptr); } + }; + +public: + template + auto as() -> std::invoke_result_t::value), CastHelper, Base *> + { + // TODO: if we do downcast to base type, then just return |this|. + return CastHelper().value(static_cast(this)); + } + + template + auto as() const -> std::invoke_result_t::value), CastHelper, const Base *> + { + // TODO: if we do downcast to base type, then just return |this|. + return CastHelper().value(static_cast(this)); + } +}; + +} // namespace DB diff --git a/dbms/src/Parsers/IAST.h b/dbms/src/Parsers/IAST.h index 18092593634..65572d922d2 100644 --- a/dbms/src/Parsers/IAST.h +++ b/dbms/src/Parsers/IAST.h @@ -4,7 +4,7 @@ #include #include #include -#include +#include #include #include @@ -32,7 +32,7 @@ class WriteBuffer; /** Element of the syntax tree (hereinafter - directed acyclic graph with elements of semantics) */ -class IAST : public std::enable_shared_from_this +class IAST : public std::enable_shared_from_this, public TypePromotion { public: ASTs children; @@ -42,20 +42,6 @@ public: IAST(const IAST &) = default; IAST & operator=(const IAST &) = default; - template - Derived * as() - { - // TODO: check, if we downcasting to base type, then just return |this|. - return typeid_cast(this); - } - - template - const Derived * as() const - { - // TODO: check, if we downcasting to base type, then just return |this|. - return typeid_cast(this); - } - /** Get the canonical name of the column if the element is a column */ String getColumnName() const; virtual void appendColumnName(WriteBuffer &) const From 4f6a494af82b16811221969ea35aa01c4d6d0264 Mon Sep 17 00:00:00 2001 From: Ivan Lezhankin Date: Fri, 15 Mar 2019 19:14:13 +0300 Subject: [PATCH 09/11] Revert references where they were before refactoring. --- dbms/programs/copier/ClusterCopier.cpp | 42 ++++++------- dbms/src/Common/TypePromotion.h | 18 +++--- dbms/src/Databases/DatabaseOrdinary.cpp | 20 +++---- dbms/src/Databases/DatabasesCommon.cpp | 42 ++++++------- dbms/src/Interpreters/AnalyzedJoin.cpp | 4 +- .../Interpreters/CrossToInnerJoinVisitor.cpp | 4 +- .../DatabaseAndTableWithAlias.cpp | 10 ++-- dbms/src/Interpreters/ExpressionAnalyzer.cpp | 44 +++++++------- .../Interpreters/GlobalSubqueriesVisitor.h | 2 +- dbms/src/Interpreters/IdentifierSemantic.cpp | 2 +- .../InJoinSubqueriesPreprocessor.cpp | 18 +++--- .../Interpreters/InterpreterAlterQuery.cpp | 14 ++--- .../Interpreters/InterpreterCheckQuery.cpp | 6 +- .../Interpreters/InterpreterCreateQuery.cpp | 54 ++++++++--------- .../Interpreters/InterpreterDescribeQuery.cpp | 4 +- .../src/Interpreters/InterpreterDropQuery.cpp | 16 ++--- .../Interpreters/InterpreterExistsQuery.cpp | 4 +- .../Interpreters/InterpreterExplainQuery.cpp | 10 ++-- .../Interpreters/InterpreterInsertQuery.cpp | 20 +++---- .../InterpreterKillQueryQuery.cpp | 12 ++-- .../Interpreters/InterpreterOptimizeQuery.cpp | 10 ++-- .../Interpreters/InterpreterRenameQuery.cpp | 10 ++-- .../Interpreters/InterpreterSelectQuery.cpp | 14 ++--- .../src/Interpreters/InterpreterSelectQuery.h | 2 +- .../InterpreterSelectWithUnionQuery.cpp | 10 ++-- dbms/src/Interpreters/InterpreterSetQuery.cpp | 12 ++-- .../InterpreterShowCreateQuery.cpp | 18 +++--- .../InterpreterShowTablesQuery.cpp | 14 ++--- .../Interpreters/InterpreterSystemQuery.cpp | 44 +++++++------- dbms/src/Interpreters/InterpreterUseQuery.cpp | 2 +- .../JoinToSubqueryTransformVisitor.cpp | 12 ++-- dbms/src/Interpreters/QueryNormalizer.cpp | 10 ++-- dbms/src/Interpreters/Set.cpp | 4 +- dbms/src/Interpreters/SyntaxAnalyzer.cpp | 44 +++++++------- .../TranslateQualifiedNamesVisitor.cpp | 8 +-- dbms/src/Interpreters/executeQuery.cpp | 2 +- dbms/src/Interpreters/loadMetadata.cpp | 6 +- dbms/src/Parsers/ASTRenameQuery.h | 6 +- dbms/src/Parsers/ASTSelectQuery.cpp | 54 ++++++++--------- dbms/src/Parsers/ASTTablesInSelectQuery.cpp | 6 +- dbms/src/Parsers/ExpressionElementParsers.cpp | 14 ++--- dbms/src/Parsers/ExpressionListParsers.cpp | 2 +- dbms/src/Parsers/ParserAlterQuery.cpp | 4 +- dbms/src/Parsers/ParserCreateQuery.cpp | 4 +- dbms/src/Parsers/ParserPartition.cpp | 2 +- dbms/src/Parsers/ParserQueryWithOutput.cpp | 16 ++--- dbms/src/Parsers/ParserSetQuery.cpp | 2 +- dbms/src/Parsers/ParserShowTablesQuery.cpp | 2 +- .../parseIdentifierOrStringLiteral.cpp | 2 +- dbms/src/Storages/AlterCommands.cpp | 60 +++++++++---------- dbms/src/Storages/ColumnsDescription.cpp | 2 +- dbms/src/Storages/Kafka/StorageKafka.cpp | 4 +- dbms/src/Storages/MergeTree/KeyCondition.cpp | 16 ++--- dbms/src/Storages/MergeTree/MergeTreeData.cpp | 28 ++++----- .../MergeTree/MergeTreeDataSelectExecutor.cpp | 24 ++++---- .../MergeTree/MergeTreeSetSkippingIndex.cpp | 18 +++--- .../MergeTree/MergeTreeWhereOptimizer.cpp | 4 +- dbms/src/Storages/MutationCommands.cpp | 8 +-- .../src/TableFunctions/TableFunctionMerge.cpp | 4 +- .../src/TableFunctions/TableFunctionMySQL.cpp | 20 +++---- .../TableFunctions/TableFunctionNumbers.cpp | 2 +- .../TableFunctions/TableFunctionRemote.cpp | 6 +- 62 files changed, 439 insertions(+), 439 deletions(-) diff --git a/dbms/programs/copier/ClusterCopier.cpp b/dbms/programs/copier/ClusterCopier.cpp index bcbf8771487..cc9f9de6485 100644 --- a/dbms/programs/copier/ClusterCopier.cpp +++ b/dbms/programs/copier/ClusterCopier.cpp @@ -483,37 +483,37 @@ String DB::TaskShard::getHostNameExample() const static bool isExtendedDefinitionStorage(const ASTPtr & storage_ast) { - const auto * storage = storage_ast->as(); - return storage->partition_by || storage->order_by || storage->sample_by; + const auto & storage = storage_ast->as(); + return storage.partition_by || storage.order_by || storage.sample_by; } static ASTPtr extractPartitionKey(const ASTPtr & storage_ast) { String storage_str = queryToString(storage_ast); - const auto * storage = storage_ast->as(); - const auto * engine = storage->engine->as(); + const auto & storage = storage_ast->as(); + const auto & engine = storage.engine->as(); - if (!endsWith(engine->name, "MergeTree")) + if (!endsWith(engine.name, "MergeTree")) { throw Exception("Unsupported engine was specified in " + storage_str + ", only *MergeTree engines are supported", ErrorCodes::BAD_ARGUMENTS); } - ASTPtr arguments_ast = engine->arguments->clone(); + ASTPtr arguments_ast = engine.arguments->clone(); ASTs & arguments = arguments_ast->children; if (isExtendedDefinitionStorage(storage_ast)) { - if (storage->partition_by) - return storage->partition_by->clone(); + if (storage.partition_by) + return storage.partition_by->clone(); static const char * all = "all"; return std::make_shared(Field(all, strlen(all))); } else { - bool is_replicated = startsWith(engine->name, "Replicated"); + bool is_replicated = startsWith(engine.name, "Replicated"); size_t min_args = is_replicated ? 3 : 1; if (arguments.size() < min_args) @@ -1184,11 +1184,11 @@ protected: for (const ASTPtr & column_ast : column_asts) { - const auto * column = column_ast->as(); + const auto & column = column_ast->as(); - if (!column->default_specifier.empty()) + if (!column.default_specifier.empty()) { - ColumnDefaultKind kind = columnDefaultKindFromString(column->default_specifier); + ColumnDefaultKind kind = columnDefaultKindFromString(column.default_specifier); if (kind == ColumnDefaultKind::Materialized || kind == ColumnDefaultKind::Alias) continue; } @@ -1197,13 +1197,13 @@ protected: } ASTPtr new_query_ast = query_ast->clone(); - auto * new_query = new_query_ast->as(); + auto & new_query = new_query_ast->as(); auto new_columns_list = std::make_shared(); new_columns_list->set(new_columns_list->columns, new_columns); new_columns_list->set(new_columns_list->indices, query_ast->as()->columns_list->indices->clone()); - new_query->replace(new_query->columns_list, new_columns_list); + new_query.replace(new_query.columns_list, new_columns_list); return new_query_ast; } @@ -1211,17 +1211,17 @@ protected: /// Replaces ENGINE and table name in a create query std::shared_ptr rewriteCreateQueryStorage(const ASTPtr & create_query_ast, const DatabaseAndTableName & new_table, const ASTPtr & new_storage_ast) { - const auto * create = create_query_ast->as(); - auto res = std::make_shared(*create); + const auto & create = create_query_ast->as(); + auto res = std::make_shared(create); - if (create->storage == nullptr || new_storage_ast == nullptr) + if (create.storage == nullptr || new_storage_ast == nullptr) throw Exception("Storage is not specified", ErrorCodes::LOGICAL_ERROR); res->database = new_table.first; res->table = new_table.second; res->children.clear(); - res->set(res->columns_list, create->columns_list->clone()); + res->set(res->columns_list, create.columns_list->clone()); res->set(res->storage, new_storage_ast->clone()); return res; @@ -1645,7 +1645,7 @@ protected: /// Try create table (if not exists) on each shard { auto create_query_push_ast = rewriteCreateQueryStorage(task_shard.current_pull_table_create_query, task_table.table_push, task_table.engine_push_ast); - create_query_push_ast->as()->if_not_exists = true; + create_query_push_ast->as().if_not_exists = true; String query = queryToString(create_query_push_ast); LOG_DEBUG(log, "Create destination tables. Query: " << query); @@ -1778,8 +1778,8 @@ protected: void dropAndCreateLocalTable(const ASTPtr & create_ast) { - const auto * create = create_ast->as(); - dropLocalTableIfExists({create->database, create->table}); + const auto & create = create_ast->as(); + dropLocalTableIfExists({create.database, create.table}); InterpreterCreateQuery interpreter(create_ast, context); interpreter.execute(); diff --git a/dbms/src/Common/TypePromotion.h b/dbms/src/Common/TypePromotion.h index e338f3b9fca..b53bc25010c 100644 --- a/dbms/src/Common/TypePromotion.h +++ b/dbms/src/Common/TypePromotion.h @@ -8,11 +8,11 @@ template class TypePromotion { private: /// Need a helper-struct to fight the lack of the function-template partial specialization. - template , bool is_const = std::is_const_v> + template > struct CastHelper; template - struct CastHelper + struct CastHelper { auto & value(Base * ptr) { return typeid_cast(*ptr); } }; @@ -20,7 +20,7 @@ private: template struct CastHelper { - auto & value(const Base * ptr) { return typeid_cast(*ptr); } + auto & value(const Base * ptr) { return typeid_cast>>>(*ptr); } }; template @@ -30,24 +30,24 @@ private: }; template - struct CastHelper + struct CastHelper { - auto * value(const Base * ptr) { return typeid_cast(ptr); } + auto * value(const Base * ptr) { return typeid_cast *>(ptr); } }; public: template - auto as() -> std::invoke_result_t::value), CastHelper, Base *> + auto as() -> std::invoke_result_t::value), CastHelper, Base *> { // TODO: if we do downcast to base type, then just return |this|. - return CastHelper().value(static_cast(this)); + return CastHelper().value(static_cast(this)); } template - auto as() const -> std::invoke_result_t::value), CastHelper, const Base *> + auto as() const -> std::invoke_result_t::value), CastHelper, const Base *> { // TODO: if we do downcast to base type, then just return |this|. - return CastHelper().value(static_cast(this)); + return CastHelper().value(static_cast(this)); } }; diff --git a/dbms/src/Databases/DatabaseOrdinary.cpp b/dbms/src/Databases/DatabaseOrdinary.cpp index 235cc3b6b51..e144ed9071e 100644 --- a/dbms/src/Databases/DatabaseOrdinary.cpp +++ b/dbms/src/Databases/DatabaseOrdinary.cpp @@ -370,9 +370,9 @@ static ASTPtr getCreateQueryFromMetadata(const String & metadata_path, const Str if (ast) { - auto * ast_create_query = ast->as(); - ast_create_query->attach = false; - ast_create_query->database = database; + auto & ast_create_query = ast->as(); + ast_create_query.attach = false; + ast_create_query.database = database; } return ast; @@ -415,7 +415,7 @@ void DatabaseOrdinary::renameTable( ASTPtr ast = getQueryFromMetadata(detail::getTableMetadataPath(metadata_path, table_name)); if (!ast) throw Exception("There is no metadata file for table " + table_name, ErrorCodes::FILE_DOESNT_EXIST); - ast->as()->table = to_table_name; + ast->as().table = to_table_name; /// NOTE Non-atomic. to_database_concrete->createTable(context, to_table_name, table, ast); @@ -533,20 +533,20 @@ void DatabaseOrdinary::alterTable( ParserCreateQuery parser; ASTPtr ast = parseQuery(parser, statement.data(), statement.data() + statement.size(), "in file " + table_metadata_path, 0); - const auto * ast_create_query = ast->as(); + const auto & ast_create_query = ast->as(); ASTPtr new_columns = InterpreterCreateQuery::formatColumns(columns); ASTPtr new_indices = InterpreterCreateQuery::formatIndices(indices); - ast_create_query->columns_list->replace(ast_create_query->columns_list->columns, new_columns); + ast_create_query.columns_list->replace(ast_create_query.columns_list->columns, new_columns); - if (ast_create_query->columns_list->indices) - ast_create_query->columns_list->replace(ast_create_query->columns_list->indices, new_indices); + if (ast_create_query.columns_list->indices) + ast_create_query.columns_list->replace(ast_create_query.columns_list->indices, new_indices); else - ast_create_query->columns_list->set(ast_create_query->columns_list->indices, new_indices); + ast_create_query.columns_list->set(ast_create_query.columns_list->indices, new_indices); if (storage_modifier) - storage_modifier(*ast_create_query->storage); + storage_modifier(*ast_create_query.storage); statement = getTableDefinitionFromCreateQuery(ast); diff --git a/dbms/src/Databases/DatabasesCommon.cpp b/dbms/src/Databases/DatabasesCommon.cpp index 482d37fa9e6..6292c4f4149 100644 --- a/dbms/src/Databases/DatabasesCommon.cpp +++ b/dbms/src/Databases/DatabasesCommon.cpp @@ -26,26 +26,26 @@ namespace ErrorCodes String getTableDefinitionFromCreateQuery(const ASTPtr & query) { ASTPtr query_clone = query->clone(); - auto * create = query_clone->as(); + auto & create = query_clone->as(); /// We remove everything that is not needed for ATTACH from the query. - create->attach = true; - create->database.clear(); - create->as_database.clear(); - create->as_table.clear(); - create->if_not_exists = false; - create->is_populate = false; - create->replace_view = false; + create.attach = true; + create.database.clear(); + create.as_database.clear(); + create.as_table.clear(); + create.if_not_exists = false; + create.is_populate = false; + create.replace_view = false; /// For views it is necessary to save the SELECT query itself, for the rest - on the contrary - if (!create->is_view && !create->is_materialized_view) - create->select = nullptr; + if (!create.is_view && !create.is_materialized_view) + create.select = nullptr; - create->format = nullptr; - create->out_file = nullptr; + create.format = nullptr; + create.out_file = nullptr; std::ostringstream statement_stream; - formatAST(*create, statement_stream, false); + formatAST(create, statement_stream, false); statement_stream << '\n'; return statement_stream.str(); } @@ -62,24 +62,24 @@ std::pair createTableFromDefinition( ParserCreateQuery parser; ASTPtr ast = parseQuery(parser, definition.data(), definition.data() + definition.size(), description_for_error_message, 0); - auto * ast_create_query = ast->as(); - ast_create_query->attach = true; - ast_create_query->database = database_name; + auto & ast_create_query = ast->as(); + ast_create_query.attach = true; + ast_create_query.database = database_name; /// We do not directly use `InterpreterCreateQuery::execute`, because /// - the database has not been created yet; /// - the code is simpler, since the query is already brought to a suitable form. - if (!ast_create_query->columns_list || !ast_create_query->columns_list->columns) + if (!ast_create_query.columns_list || !ast_create_query.columns_list->columns) throw Exception("Missing definition of columns.", ErrorCodes::EMPTY_LIST_OF_COLUMNS_PASSED); - ColumnsDescription columns = InterpreterCreateQuery::getColumnsDescription(*ast_create_query->columns_list->columns, context); + ColumnsDescription columns = InterpreterCreateQuery::getColumnsDescription(*ast_create_query.columns_list->columns, context); return { - ast_create_query->table, + ast_create_query.table, StorageFactory::instance().get( - *ast_create_query, - database_data_path, ast_create_query->table, database_name, context, context.getGlobalContext(), + ast_create_query, + database_data_path, ast_create_query.table, database_name, context, context.getGlobalContext(), columns, true, has_force_restore_data_flag) }; diff --git a/dbms/src/Interpreters/AnalyzedJoin.cpp b/dbms/src/Interpreters/AnalyzedJoin.cpp index d674432bb10..333e82690dc 100644 --- a/dbms/src/Interpreters/AnalyzedJoin.cpp +++ b/dbms/src/Interpreters/AnalyzedJoin.cpp @@ -45,13 +45,13 @@ ExpressionActionsPtr AnalyzedJoin::createJoinedBlockActions( if (!join) return nullptr; - const auto * join_params = join->table_join->as(); + const auto & join_params = join->table_join->as(); /// Create custom expression list with join keys from right table. auto expression_list = std::make_shared(); ASTs & children = expression_list->children; - if (join_params->on_expression) + if (join_params.on_expression) for (const auto & join_right_key : key_asts_right) children.emplace_back(join_right_key); diff --git a/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp b/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp index 0c11ea51b1f..dc46c95ace9 100644 --- a/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp +++ b/dbms/src/Interpreters/CrossToInnerJoinVisitor.cpp @@ -56,8 +56,8 @@ struct JoinedTable if (element->table_expression) { - const auto * expr = element->table_expression->as(); - table = DatabaseAndTableWithAlias(*expr); + const auto & expr = element->table_expression->as(); + table = DatabaseAndTableWithAlias(expr); } array_join = element->array_join; diff --git a/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp b/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp index e51ab1a7e77..47b0ead07cc 100644 --- a/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp +++ b/dbms/src/Interpreters/DatabaseAndTableWithAlias.cpp @@ -92,16 +92,16 @@ static const ASTTableExpression * getTableExpression(const ASTSelectQuery & sele if (!select.tables) return {}; - const auto * tables_in_select_query = select.tables->as(); - if (tables_in_select_query->children.size() <= table_number) + const auto & tables_in_select_query = select.tables->as(); + if (tables_in_select_query.children.size() <= table_number) return {}; - const auto * tables_element = tables_in_select_query->children[table_number]->as(); + const auto & tables_element = tables_in_select_query.children[table_number]->as(); - if (!tables_element->table_expression) + if (!tables_element.table_expression) return {}; - return tables_element->table_expression->as(); + return tables_element.table_expression->as(); } std::vector getDatabaseAndTables(const ASTSelectQuery & select_query, const String & current_database) diff --git a/dbms/src/Interpreters/ExpressionAnalyzer.cpp b/dbms/src/Interpreters/ExpressionAnalyzer.cpp index 85cc88de2d7..8e69d5ecfee 100644 --- a/dbms/src/Interpreters/ExpressionAnalyzer.cpp +++ b/dbms/src/Interpreters/ExpressionAnalyzer.cpp @@ -149,10 +149,10 @@ void ExpressionAnalyzer::analyzeAggregation() const ASTTablesInSelectQueryElement * join = select_query->join(); if (join) { - const auto * table_join = join->table_join->as(); - if (table_join->using_expression_list) - getRootActions(table_join->using_expression_list, true, temp_actions); - if (table_join->on_expression) + const auto & table_join = join->table_join->as(); + if (table_join.using_expression_list) + getRootActions(table_join.using_expression_list, true, temp_actions); + if (table_join.on_expression) for (const auto & key_ast : analyzedJoin().key_asts_left) getRootActions(key_ast, true, temp_actions); @@ -536,33 +536,33 @@ bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_ty initChain(chain, source_columns); ExpressionActionsChain::Step & step = chain.steps.back(); - const auto * join_element = select_query->join()->as(); - auto * join_params = join_element->table_join->as(); + const auto & join_element = select_query->join()->as(); + auto & join_params = join_element.table_join->as(); - if (join_params->strictness == ASTTableJoin::Strictness::Unspecified && join_params->kind != ASTTableJoin::Kind::Cross) + if (join_params.strictness == ASTTableJoin::Strictness::Unspecified && join_params.kind != ASTTableJoin::Kind::Cross) { if (settings.join_default_strictness == "ANY") - join_params->strictness = ASTTableJoin::Strictness::Any; + join_params.strictness = ASTTableJoin::Strictness::Any; else if (settings.join_default_strictness == "ALL") - join_params->strictness = ASTTableJoin::Strictness::All; + join_params.strictness = ASTTableJoin::Strictness::All; else throw Exception("Expected ANY or ALL in JOIN section, because setting (join_default_strictness) is empty", DB::ErrorCodes::EXPECTED_ALL_OR_ANY); } - const auto * table_to_join = join_element->table_expression->as(); + const auto & table_to_join = join_element.table_expression->as(); - getActionsFromJoinKeys(*join_params, only_types, step.actions); + getActionsFromJoinKeys(join_params, only_types, step.actions); /// Two JOINs are not supported with the same subquery, but different USINGs. - auto join_hash = join_element->getTreeHash(); + auto join_hash = join_element.getTreeHash(); SubqueryForSet & subquery_for_set = subqueries_for_sets[toString(join_hash.first) + "_" + toString(join_hash.second)]; /// Special case - if table name is specified on the right of JOIN, then the table has the type Join (the previously prepared mapping). /// TODO This syntax does not support specifying a database name. - if (table_to_join->database_and_table_name) + if (table_to_join.database_and_table_name) { - DatabaseAndTableWithAlias database_table(table_to_join->database_and_table_name); + DatabaseAndTableWithAlias database_table(table_to_join.database_and_table_name); StoragePtr table = context.tryGetTable(database_table.database, database_table.table); if (table) @@ -571,7 +571,7 @@ bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_ty if (storage_join) { - storage_join->assertCompatible(join_params->kind, join_params->strictness); + storage_join->assertCompatible(join_params.kind, join_params.strictness); /// TODO Check the set of keys. JoinPtr & join = storage_join->getJoin(); @@ -596,12 +596,12 @@ bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_ty { ASTPtr table; - if (table_to_join->subquery) - table = table_to_join->subquery; - else if (table_to_join->table_function) - table = table_to_join->table_function; - else if (table_to_join->database_and_table_name) - table = table_to_join->database_and_table_name; + if (table_to_join.subquery) + table = table_to_join.subquery; + else if (table_to_join.table_function) + table = table_to_join.table_function; + else if (table_to_join.database_and_table_name) + table = table_to_join.database_and_table_name; Names action_columns = joined_block_actions->getRequiredColumns(); NameSet required_columns(action_columns.begin(), action_columns.end()); @@ -619,7 +619,7 @@ bool ExpressionAnalyzer::appendJoin(ExpressionActionsChain & chain, bool only_ty /// TODO You do not need to set this up when JOIN is only needed on remote servers. subquery_for_set.join = std::make_shared(analyzedJoin().key_names_right, settings.join_use_nulls, - settings.size_limits_for_join, join_params->kind, join_params->strictness); + settings.size_limits_for_join, join_params.kind, join_params.strictness); subquery_for_set.join->setSampleBlock(sample_block); subquery_for_set.joined_block_actions = joined_block_actions; } diff --git a/dbms/src/Interpreters/GlobalSubqueriesVisitor.h b/dbms/src/Interpreters/GlobalSubqueriesVisitor.h index db56631061a..c99f8d95e49 100644 --- a/dbms/src/Interpreters/GlobalSubqueriesVisitor.h +++ b/dbms/src/Interpreters/GlobalSubqueriesVisitor.h @@ -168,7 +168,7 @@ private: /// GLOBAL JOIN static void visit(ASTTablesInSelectQueryElement & table_elem, ASTPtr &, Data & data) { - if (table_elem.table_join && table_elem.table_join->as()->locality == ASTTableJoin::Locality::Global) + if (table_elem.table_join && table_elem.table_join->as().locality == ASTTableJoin::Locality::Global) { data.addExternalStorage(table_elem.table_expression); data.has_global_subqueries = true; diff --git a/dbms/src/Interpreters/IdentifierSemantic.cpp b/dbms/src/Interpreters/IdentifierSemantic.cpp index debc9ceccca..361462c0d1d 100644 --- a/dbms/src/Interpreters/IdentifierSemantic.cpp +++ b/dbms/src/Interpreters/IdentifierSemantic.cpp @@ -144,7 +144,7 @@ void IdentifierSemantic::setColumnLongName(ASTIdentifier & identifier, const Dat String IdentifierSemantic::columnNormalName(const ASTIdentifier & identifier, const DatabaseAndTableWithAlias & db_and_table) { ASTPtr copy = identifier.clone(); - setColumnNormalName(*copy->as(), db_and_table); + setColumnNormalName(copy->as(), db_and_table); return copy->getAliasOrColumnName(); } diff --git a/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp b/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp index 556882b6774..9e814b00b63 100644 --- a/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp +++ b/dbms/src/Interpreters/InJoinSubqueriesPreprocessor.cpp @@ -44,12 +44,12 @@ void forEachNonGlobalSubquery(IAST * node, F && f) { if (join->table_join && join->table_expression) { - auto * table_join = join->table_join->as(); - if (table_join->locality != ASTTableJoin::Locality::Global) + auto & table_join = join->table_join->as(); + if (table_join.locality != ASTTableJoin::Locality::Global) { auto & subquery = join->table_expression->as()->subquery; if (subquery) - f(subquery.get(), nullptr, table_join); + f(subquery.get(), nullptr, &table_join); } return; } @@ -103,15 +103,15 @@ void InJoinSubqueriesPreprocessor::process(ASTSelectQuery * query) const if (!query->tables) return; - const auto * tables_in_select_query = query->tables->as(); - if (tables_in_select_query->children.empty()) + const auto & tables_in_select_query = query->tables->as(); + if (tables_in_select_query.children.empty()) return; - const auto * tables_element = tables_in_select_query->children[0]->as(); - if (!tables_element->table_expression) + const auto & tables_element = tables_in_select_query.children[0]->as(); + if (!tables_element.table_expression) return; - const auto * table_expression = tables_element->table_expression->as(); + const auto * table_expression = tables_element.table_expression->as(); /// If not ordinary table, skip it. if (!table_expression->database_and_table_name) @@ -157,7 +157,7 @@ void InJoinSubqueriesPreprocessor::process(ASTSelectQuery * query) const throw Exception("Logical error: unexpected function name " + concrete->name, ErrorCodes::LOGICAL_ERROR); } else if (table_join) - table_join->as()->locality = ASTTableJoin::Locality::Global; + table_join->as().locality = ASTTableJoin::Locality::Global; else throw Exception("Logical error: unexpected AST node", ErrorCodes::LOGICAL_ERROR); } diff --git a/dbms/src/Interpreters/InterpreterAlterQuery.cpp b/dbms/src/Interpreters/InterpreterAlterQuery.cpp index c51bceba2e0..8751ff067b1 100644 --- a/dbms/src/Interpreters/InterpreterAlterQuery.cpp +++ b/dbms/src/Interpreters/InterpreterAlterQuery.cpp @@ -30,25 +30,25 @@ InterpreterAlterQuery::InterpreterAlterQuery(const ASTPtr & query_ptr_, const Co BlockIO InterpreterAlterQuery::execute() { - const auto * alter = query_ptr->as(); + const auto & alter = query_ptr->as(); - if (!alter->cluster.empty()) - return executeDDLQueryOnCluster(query_ptr, context, {alter->database}); + if (!alter.cluster.empty()) + return executeDDLQueryOnCluster(query_ptr, context, {alter.database}); - const String & table_name = alter->table; - String database_name = alter->database.empty() ? context.getCurrentDatabase() : alter->database; + const String & table_name = alter.table; + String database_name = alter.database.empty() ? context.getCurrentDatabase() : alter.database; StoragePtr table = context.getTable(database_name, table_name); /// Add default database to table identifiers that we can encounter in e.g. default expressions, /// mutation expression, etc. AddDefaultDatabaseVisitor visitor(database_name); - ASTPtr command_list_ptr = alter->command_list->ptr(); + ASTPtr command_list_ptr = alter.command_list->ptr(); visitor.visit(command_list_ptr); AlterCommands alter_commands; PartitionCommands partition_commands; MutationCommands mutation_commands; - for (ASTAlterCommand * command_ast : alter->command_list->commands) + for (ASTAlterCommand * command_ast : alter.command_list->commands) { if (auto alter_command = AlterCommand::parse(command_ast)) alter_commands.emplace_back(std::move(*alter_command)); diff --git a/dbms/src/Interpreters/InterpreterCheckQuery.cpp b/dbms/src/Interpreters/InterpreterCheckQuery.cpp index 1998ba897b2..c99c74fa33a 100644 --- a/dbms/src/Interpreters/InterpreterCheckQuery.cpp +++ b/dbms/src/Interpreters/InterpreterCheckQuery.cpp @@ -19,9 +19,9 @@ InterpreterCheckQuery::InterpreterCheckQuery(const ASTPtr & query_ptr_, const Co BlockIO InterpreterCheckQuery::execute() { - const auto * alter = query_ptr->as(); - const String & table_name = alter->table; - String database_name = alter->database.empty() ? context.getCurrentDatabase() : alter->database; + const auto & alter = query_ptr->as(); + const String & table_name = alter.table; + String database_name = alter.database.empty() ? context.getCurrentDatabase() : alter.database; StoragePtr table = context.getTable(database_name, table_name); diff --git a/dbms/src/Interpreters/InterpreterCreateQuery.cpp b/dbms/src/Interpreters/InterpreterCreateQuery.cpp index 6b0c2c2f6b9..4e669faa512 100644 --- a/dbms/src/Interpreters/InterpreterCreateQuery.cpp +++ b/dbms/src/Interpreters/InterpreterCreateQuery.cpp @@ -197,51 +197,51 @@ static ColumnsDeclarationAndModifiers parseColumns(const ASTExpressionList & col for (const auto & ast : column_list_ast.children) { - auto * col_decl = ast->as(); + auto & col_decl = ast->as(); DataTypePtr column_type = nullptr; - if (col_decl->type) + if (col_decl.type) { - column_type = DataTypeFactory::instance().get(col_decl->type); - columns.emplace_back(col_decl->name, column_type); + column_type = DataTypeFactory::instance().get(col_decl.type); + columns.emplace_back(col_decl.name, column_type); } else /// we're creating dummy DataTypeUInt8 in order to prevent the NullPointerException in ExpressionActions - columns.emplace_back(col_decl->name, std::make_shared()); + columns.emplace_back(col_decl.name, std::make_shared()); /// add column to postprocessing if there is a default_expression specified - if (col_decl->default_expression) + if (col_decl.default_expression) { - defaulted_columns.emplace_back(&columns.back(), col_decl); + defaulted_columns.emplace_back(&columns.back(), &col_decl); /** for columns with explicitly-specified type create two expressions: * 1. default_expression aliased as column name with _tmp suffix * 2. conversion of expression (1) to explicitly-specified type alias as column name */ - if (col_decl->type) + if (col_decl.type) { - const auto & final_column_name = col_decl->name; + const auto & final_column_name = col_decl.name; const auto tmp_column_name = final_column_name + "_tmp"; const auto data_type_ptr = columns.back().type.get(); default_expr_list->children.emplace_back(setAlias( makeASTFunction("CAST", std::make_shared(tmp_column_name), std::make_shared(data_type_ptr->getName())), final_column_name)); - default_expr_list->children.emplace_back(setAlias(col_decl->default_expression->clone(), tmp_column_name)); + default_expr_list->children.emplace_back(setAlias(col_decl.default_expression->clone(), tmp_column_name)); } else - default_expr_list->children.emplace_back(setAlias(col_decl->default_expression->clone(), col_decl->name)); + default_expr_list->children.emplace_back(setAlias(col_decl.default_expression->clone(), col_decl.name)); } - if (col_decl->codec) + if (col_decl.codec) { - auto codec = CompressionCodecFactory::instance().get(col_decl->codec, column_type); - codecs.emplace(col_decl->name, codec); + auto codec = CompressionCodecFactory::instance().get(col_decl.codec, column_type); + codecs.emplace(col_decl.name, codec); } - if (col_decl->comment) + if (col_decl.comment) { - if (auto comment_str = col_decl->comment->as()->value.get(); !comment_str.empty()) - comments.emplace(col_decl->name, comment_str); + if (auto comment_str = col_decl.comment->as().value.get(); !comment_str.empty()) + comments.emplace(col_decl.name, comment_str); } } @@ -526,14 +526,14 @@ void InterpreterCreateQuery::setEngine(ASTCreateQuery & create) const String as_table_name = create.as_table; ASTPtr as_create_ptr = context.getCreateTableQuery(as_database_name, as_table_name); - const auto * as_create = as_create_ptr->as(); + const auto & as_create = as_create_ptr->as(); - if (as_create->is_view) + if (as_create.is_view) throw Exception( "Cannot CREATE a table AS " + as_database_name + "." + as_table_name + ", it is a View", ErrorCodes::INCORRECT_QUERY); - create.set(create.storage, as_create->storage->ptr()); + create.set(create.storage, as_create.storage->ptr()); } } @@ -566,7 +566,7 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) { // Table SQL definition is available even if the table is detached auto query = context.getCreateTableQuery(database_name, table_name); - create = *query->as(); // Copy the saved create query, but use ATTACH instead of CREATE + create = query->as(); // Copy the saved create query, but use ATTACH instead of CREATE create.attach = true; } @@ -694,17 +694,17 @@ BlockIO InterpreterCreateQuery::createTable(ASTCreateQuery & create) BlockIO InterpreterCreateQuery::execute() { - auto * create = query_ptr->as(); - checkAccess(*create); - ASTQueryWithOutput::resetOutputASTIfExist(*create); + auto & create = query_ptr->as(); + checkAccess(create); + ASTQueryWithOutput::resetOutputASTIfExist(create); /// CREATE|ATTACH DATABASE - if (!create->database.empty() && create->table.empty()) + if (!create.database.empty() && create.table.empty()) { - return createDatabase(*create); + return createDatabase(create); } else - return createTable(*create); + return createTable(create); } diff --git a/dbms/src/Interpreters/InterpreterDescribeQuery.cpp b/dbms/src/Interpreters/InterpreterDescribeQuery.cpp index 5054c8e7274..f91fb1c0a2a 100644 --- a/dbms/src/Interpreters/InterpreterDescribeQuery.cpp +++ b/dbms/src/Interpreters/InterpreterDescribeQuery.cpp @@ -58,7 +58,7 @@ Block InterpreterDescribeQuery::getSampleBlock() BlockInputStreamPtr InterpreterDescribeQuery::executeImpl() { - const auto * ast = query_ptr->as(); + const auto & ast = query_ptr->as(); NamesAndTypesList columns; ColumnDefaults column_defaults; @@ -66,7 +66,7 @@ BlockInputStreamPtr InterpreterDescribeQuery::executeImpl() ColumnCodecs column_codecs; StoragePtr table; - const auto * table_expression = ast->table_expression->as(); + const auto * table_expression = ast.table_expression->as(); if (table_expression->subquery) { diff --git a/dbms/src/Interpreters/InterpreterDropQuery.cpp b/dbms/src/Interpreters/InterpreterDropQuery.cpp index 68ce449766f..91213b6100e 100644 --- a/dbms/src/Interpreters/InterpreterDropQuery.cpp +++ b/dbms/src/Interpreters/InterpreterDropQuery.cpp @@ -31,17 +31,17 @@ InterpreterDropQuery::InterpreterDropQuery(const ASTPtr & query_ptr_, Context & BlockIO InterpreterDropQuery::execute() { - auto * drop = query_ptr->as(); + auto & drop = query_ptr->as(); - checkAccess(*drop); + checkAccess(drop); - if (!drop->cluster.empty()) - return executeDDLQueryOnCluster(query_ptr, context, {drop->database}); + if (!drop.cluster.empty()) + return executeDDLQueryOnCluster(query_ptr, context, {drop.database}); - if (!drop->table.empty()) - return executeToTable(drop->database, drop->table, drop->kind, drop->if_exists, drop->temporary, drop->no_ddl_lock); - else if (!drop->database.empty()) - return executeToDatabase(drop->database, drop->kind, drop->if_exists); + if (!drop.table.empty()) + return executeToTable(drop.database, drop.table, drop.kind, drop.if_exists, drop.temporary, drop.no_ddl_lock); + else if (!drop.database.empty()) + return executeToDatabase(drop.database, drop.kind, drop.if_exists); else throw Exception("Database and table names is empty.", ErrorCodes::LOGICAL_ERROR); } diff --git a/dbms/src/Interpreters/InterpreterExistsQuery.cpp b/dbms/src/Interpreters/InterpreterExistsQuery.cpp index 2d4d7a51437..27c78fe430d 100644 --- a/dbms/src/Interpreters/InterpreterExistsQuery.cpp +++ b/dbms/src/Interpreters/InterpreterExistsQuery.cpp @@ -32,8 +32,8 @@ Block InterpreterExistsQuery::getSampleBlock() BlockInputStreamPtr InterpreterExistsQuery::executeImpl() { - const auto * ast = query_ptr->as(); - bool res = ast->temporary ? context.isExternalTableExist(ast->table) : context.isTableExist(ast->database, ast->table); + const auto & ast = query_ptr->as(); + bool res = ast.temporary ? context.isExternalTableExist(ast.table) : context.isTableExist(ast.database, ast.table); return std::make_shared(Block{{ ColumnUInt8::create(1, res), diff --git a/dbms/src/Interpreters/InterpreterExplainQuery.cpp b/dbms/src/Interpreters/InterpreterExplainQuery.cpp index 28391d3eac8..971de38d11a 100644 --- a/dbms/src/Interpreters/InterpreterExplainQuery.cpp +++ b/dbms/src/Interpreters/InterpreterExplainQuery.cpp @@ -39,19 +39,19 @@ Block InterpreterExplainQuery::getSampleBlock() BlockInputStreamPtr InterpreterExplainQuery::executeImpl() { - const auto * ast = query->as(); + const auto & ast = query->as(); Block sample_block = getSampleBlock(); MutableColumns res_columns = sample_block.cloneEmptyColumns(); std::stringstream ss; - if (ast->getKind() == ASTExplainQuery::ParsedAST) + if (ast.getKind() == ASTExplainQuery::ParsedAST) { - dumpAST(*ast, ss); + dumpAST(ast, ss); } - else if (ast->getKind() == ASTExplainQuery::AnalyzedSyntax) + else if (ast.getKind() == ASTExplainQuery::AnalyzedSyntax) { - InterpreterSelectWithUnionQuery interpreter(ast->children.at(0), context, {}, QueryProcessingStage::FetchColumns, 0, true, true); + InterpreterSelectWithUnionQuery interpreter(ast.children.at(0), context, {}, QueryProcessingStage::FetchColumns, 0, true, true); interpreter.getQuery()->format(IAST::FormatSettings(ss, false)); } diff --git a/dbms/src/Interpreters/InterpreterInsertQuery.cpp b/dbms/src/Interpreters/InterpreterInsertQuery.cpp index 14c385f344d..d5b67e5518a 100644 --- a/dbms/src/Interpreters/InterpreterInsertQuery.cpp +++ b/dbms/src/Interpreters/InterpreterInsertQuery.cpp @@ -92,16 +92,16 @@ Block InterpreterInsertQuery::getSampleBlock(const ASTInsertQuery & query, const BlockIO InterpreterInsertQuery::execute() { - const auto * query = query_ptr->as(); - checkAccess(*query); - StoragePtr table = getTable(*query); + const auto & query = query_ptr->as(); + checkAccess(query); + StoragePtr table = getTable(query); auto table_lock = table->lockStructureForShare(true, context.getCurrentQueryId()); /// We create a pipeline of several streams, into which we will write data. BlockOutputStreamPtr out; - out = std::make_shared(query->database, query->table, table, context, query_ptr, query->no_destination); + out = std::make_shared(query.database, query.table, table, context, query_ptr, query.no_destination); /// Do not squash blocks if it is a sync INSERT into Distributed, since it lead to double bufferization on client and server side. /// Client-side bufferization might cause excessive timeouts (especially in case of big blocks). @@ -110,7 +110,7 @@ BlockIO InterpreterInsertQuery::execute() out = std::make_shared( out, table->getSampleBlock(), context.getSettingsRef().min_insert_block_size_rows, context.getSettingsRef().min_insert_block_size_bytes); } - auto query_sample_block = getSampleBlock(*query, table); + auto query_sample_block = getSampleBlock(query, table); /// Actually we don't know structure of input blocks from query/table, /// because some clients break insertion protocol (columns != header) @@ -125,10 +125,10 @@ BlockIO InterpreterInsertQuery::execute() res.out = std::move(out); /// What type of query: INSERT or INSERT SELECT? - if (query->select) + if (query.select) { /// Passing 1 as subquery_depth will disable limiting size of intermediate result. - InterpreterSelectWithUnionQuery interpreter_select{query->select, context, {}, QueryProcessingStage::Complete, 1}; + InterpreterSelectWithUnionQuery interpreter_select{query.select, context, {}, QueryProcessingStage::Complete, 1}; res.in = interpreter_select.execute().in; @@ -145,7 +145,7 @@ BlockIO InterpreterInsertQuery::execute() throw Exception("Cannot insert column " + name_type.name + ", because it is MATERIALIZED column.", ErrorCodes::ILLEGAL_COLUMN); } } - else if (query->data && !query->has_tail) /// can execute without additional data + else if (query.data && !query.has_tail) /// can execute without additional data { res.in = std::make_shared(query_ptr, nullptr, query_sample_block, context); res.in = std::make_shared(res.in, res.out); @@ -171,8 +171,8 @@ void InterpreterInsertQuery::checkAccess(const ASTInsertQuery & query) std::pair InterpreterInsertQuery::getDatabaseTable() const { - const auto * query = query_ptr->as(); - return {query->database, query->table}; + const auto & query = query_ptr->as(); + return {query.database, query.table}; } } diff --git a/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp b/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp index 38b00e0b65f..89339668088 100644 --- a/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp +++ b/dbms/src/Interpreters/InterpreterKillQueryQuery.cpp @@ -172,13 +172,13 @@ public: BlockIO InterpreterKillQueryQuery::execute() { - const auto * query = query_ptr->as(); + const auto & query = query_ptr->as(); - if (!query->cluster.empty()) + if (!query.cluster.empty()) return executeDDLQueryOnCluster(query_ptr, context, {"system"}); BlockIO res_io; - switch (query->type) + switch (query.type) { case ASTKillQueryQuery::Type::Query: { @@ -192,13 +192,13 @@ BlockIO InterpreterKillQueryQuery::execute() auto header = processes_block.cloneEmpty(); header.insert(0, {ColumnString::create(), std::make_shared(), "kill_status"}); - if (!query->sync || query->test) + if (!query.sync || query.test) { MutableColumns res_columns = header.cloneEmptyColumns(); for (const auto & query_desc : queries_to_stop) { - auto code = (query->test) ? CancellationCode::Unknown : process_list.sendCancelToQuery(query_desc.query_id, query_desc.user, true); + auto code = (query.test) ? CancellationCode::Unknown : process_list.sendCancelToQuery(query_desc.query_id, query_desc.user, true); insertResultRow(query_desc.source_num, code, processes_block, header, res_columns); } @@ -237,7 +237,7 @@ BlockIO InterpreterKillQueryQuery::execute() auto mutation_id = mutation_id_col.getDataAt(i).toString(); CancellationCode code = CancellationCode::Unknown; - if (!query->test) + if (!query.test) { auto storage = context.tryGetTable(database_name, table_name); if (!storage) diff --git a/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp b/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp index 6d39ce3ee7a..7326bb62924 100644 --- a/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp +++ b/dbms/src/Interpreters/InterpreterOptimizeQuery.cpp @@ -17,14 +17,14 @@ namespace ErrorCodes BlockIO InterpreterOptimizeQuery::execute() { - const auto * ast = query_ptr->as(); + const auto & ast = query_ptr->as(); - if (!ast->cluster.empty()) - return executeDDLQueryOnCluster(query_ptr, context, {ast->database}); + if (!ast.cluster.empty()) + return executeDDLQueryOnCluster(query_ptr, context, {ast.database}); - StoragePtr table = context.getTable(ast->database, ast->table); + StoragePtr table = context.getTable(ast.database, ast.table); auto table_lock = table->lockStructureForShare(true, context.getCurrentQueryId()); - table->optimize(query_ptr, ast->partition, ast->final, ast->deduplicate, context); + table->optimize(query_ptr, ast.partition, ast.final, ast.deduplicate, context); return {}; } diff --git a/dbms/src/Interpreters/InterpreterRenameQuery.cpp b/dbms/src/Interpreters/InterpreterRenameQuery.cpp index 6cdd59ea68a..360adf45194 100644 --- a/dbms/src/Interpreters/InterpreterRenameQuery.cpp +++ b/dbms/src/Interpreters/InterpreterRenameQuery.cpp @@ -36,12 +36,12 @@ struct RenameDescription BlockIO InterpreterRenameQuery::execute() { - const auto * rename = query_ptr->as(); + const auto & rename = query_ptr->as(); - if (!rename->cluster.empty()) + if (!rename.cluster.empty()) { NameSet databases; - for (const auto & elem : rename->elements) + for (const auto & elem : rename.elements) { databases.emplace(elem.from.database); databases.emplace(elem.to.database); @@ -58,7 +58,7 @@ BlockIO InterpreterRenameQuery::execute() */ std::vector descriptions; - descriptions.reserve(rename->elements.size()); + descriptions.reserve(rename.elements.size()); /// To avoid deadlocks, we must acquire locks for tables in same order in any different RENAMES. struct UniqueTableName @@ -80,7 +80,7 @@ BlockIO InterpreterRenameQuery::execute() /// Don't allow to drop tables (that we are renaming); don't allow to create tables in places where tables will be renamed. std::map> table_guards; - for (const auto & elem : rename->elements) + for (const auto & elem : rename.elements) { descriptions.emplace_back(elem, current_database); diff --git a/dbms/src/Interpreters/InterpreterSelectQuery.cpp b/dbms/src/Interpreters/InterpreterSelectQuery.cpp index dc239a22d32..7dcd70dfc39 100644 --- a/dbms/src/Interpreters/InterpreterSelectQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSelectQuery.cpp @@ -582,8 +582,8 @@ void InterpreterSelectQuery::executeImpl(Pipeline & pipeline, const BlockInputSt { if (expressions.hasJoin()) { - const auto * join = query.join()->table_join->as(); - if (isRightOrFull(join->kind)) + const auto & join = query.join()->table_join->as(); + if (isRightOrFull(join.kind)) pipeline.stream_with_non_joined_data = expressions.before_join->createStreamWithNonJoinedDataIfFullOrRightJoin( pipeline.firstStream()->getHeader(), settings.max_block_size); @@ -1285,13 +1285,13 @@ static SortDescription getSortDescription(const ASTSelectQuery & query) for (const auto & elem : query.order_expression_list->children) { String name = elem->children.front()->getColumnName(); - const auto * order_by_elem = elem->as(); + const auto & order_by_elem = elem->as(); std::shared_ptr collator; - if (order_by_elem->collation) - collator = std::make_shared(order_by_elem->collation->as()->value.get()); + if (order_by_elem.collation) + collator = std::make_shared(order_by_elem.collation->as().value.get()); - order_descr.emplace_back(name, order_by_elem->direction, order_by_elem->nulls_direction, collator); + order_descr.emplace_back(name, order_by_elem.direction, order_by_elem.nulls_direction, collator); } return order_descr; @@ -1458,7 +1458,7 @@ bool hasWithTotalsInAnySubqueryInFromClause(const ASTSelectQuery & query) if (const auto * ast_union = query_table->as()) { for (const auto & elem : ast_union->list_of_selects->children) - if (hasWithTotalsInAnySubqueryInFromClause(*elem->as())) + if (hasWithTotalsInAnySubqueryInFromClause(elem->as())) return true; } } diff --git a/dbms/src/Interpreters/InterpreterSelectQuery.h b/dbms/src/Interpreters/InterpreterSelectQuery.h index 03e13ba8eac..fa4651c12ff 100644 --- a/dbms/src/Interpreters/InterpreterSelectQuery.h +++ b/dbms/src/Interpreters/InterpreterSelectQuery.h @@ -99,7 +99,7 @@ private: bool only_analyze_, bool modify_inplace); - ASTSelectQuery & getSelectQuery() { return *query_ptr->as(); } + ASTSelectQuery & getSelectQuery() { return query_ptr->as(); } struct Pipeline diff --git a/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp b/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp index 50fe7cd0fac..34918023d15 100644 --- a/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSelectWithUnionQuery.cpp @@ -36,9 +36,9 @@ InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery( to_stage(to_stage_), subquery_depth(subquery_depth_) { - const auto * ast = query_ptr->as(); + const auto & ast = query_ptr->as(); - size_t num_selects = ast->list_of_selects->children.size(); + size_t num_selects = ast.list_of_selects->children.size(); if (!num_selects) throw Exception("Logical error: no children in ASTSelectWithUnionQuery", ErrorCodes::LOGICAL_ERROR); @@ -57,7 +57,7 @@ InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery( /// We use it to determine positions of 'required_result_column_names' in SELECT clause. Block full_result_header = InterpreterSelectQuery( - ast->list_of_selects->children.at(0), context, Names(), to_stage, subquery_depth, true).getSampleBlock(); + ast.list_of_selects->children.at(0), context, Names(), to_stage, subquery_depth, true).getSampleBlock(); std::vector positions_of_required_result_columns(required_result_column_names.size()); for (size_t required_result_num = 0, size = required_result_column_names.size(); required_result_num < size; ++required_result_num) @@ -66,7 +66,7 @@ InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery( for (size_t query_num = 1; query_num < num_selects; ++query_num) { Block full_result_header_for_current_select = InterpreterSelectQuery( - ast->list_of_selects->children.at(query_num), context, Names(), to_stage, subquery_depth, true).getSampleBlock(); + ast.list_of_selects->children.at(query_num), context, Names(), to_stage, subquery_depth, true).getSampleBlock(); if (full_result_header_for_current_select.columns() != full_result_header.columns()) throw Exception("Different number of columns in UNION ALL elements:\n" @@ -87,7 +87,7 @@ InterpreterSelectWithUnionQuery::InterpreterSelectWithUnionQuery( = query_num == 0 ? required_result_column_names : required_result_column_names_for_other_selects[query_num]; nested_interpreters.emplace_back(std::make_unique( - ast->list_of_selects->children.at(query_num), + ast.list_of_selects->children.at(query_num), context, current_required_result_column_names, to_stage, diff --git a/dbms/src/Interpreters/InterpreterSetQuery.cpp b/dbms/src/Interpreters/InterpreterSetQuery.cpp index 4dc80f07834..08b5bc5a620 100644 --- a/dbms/src/Interpreters/InterpreterSetQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSetQuery.cpp @@ -16,12 +16,12 @@ namespace ErrorCodes BlockIO InterpreterSetQuery::execute() { - const auto * ast = query_ptr->as(); + const auto & ast = query_ptr->as(); - checkAccess(*ast); + checkAccess(ast); Context & target = context.getSessionContext(); - for (const auto & change : ast->changes) + for (const auto & change : ast.changes) target.setSetting(change.name, change.value); return {}; @@ -61,11 +61,11 @@ void InterpreterSetQuery::checkAccess(const ASTSetQuery & ast) void InterpreterSetQuery::executeForCurrentContext() { - const auto * ast = query_ptr->as(); + const auto & ast = query_ptr->as(); - checkAccess(*ast); + checkAccess(ast); - for (const auto & change : ast->changes) + for (const auto & change : ast.changes) context.setSetting(change.name, change.value); } diff --git a/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp b/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp index 8be3b90ba9e..74299ffaf4a 100644 --- a/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp +++ b/dbms/src/Interpreters/InterpreterShowCreateQuery.cpp @@ -43,21 +43,21 @@ Block InterpreterShowCreateQuery::getSampleBlock() BlockInputStreamPtr InterpreterShowCreateQuery::executeImpl() { /// FIXME: try to prettify this cast using `as<>()` - const auto * ast = dynamic_cast(query_ptr.get()); + const auto & ast = dynamic_cast(*query_ptr); - if (ast->temporary && !ast->database.empty()) + if (ast.temporary && !ast.database.empty()) throw Exception("Temporary databases are not possible.", ErrorCodes::SYNTAX_ERROR); ASTPtr create_query; - if (ast->temporary) - create_query = context.getCreateExternalTableQuery(ast->table); - else if (ast->table.empty()) - create_query = context.getCreateDatabaseQuery(ast->database); + if (ast.temporary) + create_query = context.getCreateExternalTableQuery(ast.table); + else if (ast.table.empty()) + create_query = context.getCreateDatabaseQuery(ast.database); else - create_query = context.getCreateTableQuery(ast->database, ast->table); + create_query = context.getCreateTableQuery(ast.database, ast.table); - if (!create_query && ast->temporary) - throw Exception("Unable to show the create query of " + ast->table + ". Maybe it was created by the system.", ErrorCodes::THERE_IS_NO_QUERY); + if (!create_query && ast.temporary) + throw Exception("Unable to show the create query of " + ast.table + ". Maybe it was created by the system.", ErrorCodes::THERE_IS_NO_QUERY); std::stringstream stream; formatAST(*create_query, stream, false, true); diff --git a/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp b/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp index 8214e56395f..774edcc3390 100644 --- a/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp +++ b/dbms/src/Interpreters/InterpreterShowTablesQuery.cpp @@ -25,16 +25,16 @@ InterpreterShowTablesQuery::InterpreterShowTablesQuery(const ASTPtr & query_ptr_ String InterpreterShowTablesQuery::getRewrittenQuery() { - const auto * query = query_ptr->as(); + const auto & query = query_ptr->as(); /// SHOW DATABASES - if (query->databases) + if (query.databases) return "SELECT name FROM system.databases"; - if (query->temporary && !query->from.empty()) + if (query.temporary && !query.from.empty()) throw Exception("The `FROM` and `TEMPORARY` cannot be used together in `SHOW TABLES`", ErrorCodes::SYNTAX_ERROR); - String database = query->from.empty() ? context.getCurrentDatabase() : query->from; + String database = query.from.empty() ? context.getCurrentDatabase() : query.from; /** The parameter check_database_access_rights is reset when the SHOW TABLES query is processed, * So that all clients can see a list of all databases and tables in them regardless of their access rights @@ -45,13 +45,13 @@ String InterpreterShowTablesQuery::getRewrittenQuery() std::stringstream rewritten_query; rewritten_query << "SELECT name FROM system.tables WHERE "; - if (query->temporary) + if (query.temporary) rewritten_query << "is_temporary"; else rewritten_query << "database = " << std::quoted(database, '\''); - if (!query->like.empty()) - rewritten_query << " AND name " << (query->not_like ? "NOT " : "") << "LIKE " << std::quoted(query->like, '\''); + if (!query.like.empty()) + rewritten_query << " AND name " << (query.not_like ? "NOT " : "") << "LIKE " << std::quoted(query.like, '\''); return rewritten_query.str(); } diff --git a/dbms/src/Interpreters/InterpreterSystemQuery.cpp b/dbms/src/Interpreters/InterpreterSystemQuery.cpp index 7d01d058c31..6bb0b3474fc 100644 --- a/dbms/src/Interpreters/InterpreterSystemQuery.cpp +++ b/dbms/src/Interpreters/InterpreterSystemQuery.cpp @@ -117,7 +117,7 @@ InterpreterSystemQuery::InterpreterSystemQuery(const ASTPtr & query_ptr_, Contex BlockIO InterpreterSystemQuery::execute() { - auto * query = query_ptr->as(); + auto & query = query_ptr->as(); using Type = ASTSystemQuery::Type; @@ -126,10 +126,10 @@ BlockIO InterpreterSystemQuery::execute() system_context.setSetting("profile", context.getSystemProfileName()); /// Make canonical query for simpler processing - if (!query->target_table.empty() && query->target_database.empty()) - query->target_database = context.getCurrentDatabase(); + if (!query.target_table.empty() && query.target_database.empty()) + query.target_database = context.getCurrentDatabase(); - switch (query->type) + switch (query.type) { case Type::SHUTDOWN: if (kill(0, SIGTERM)) @@ -156,7 +156,7 @@ BlockIO InterpreterSystemQuery::execute() break; #endif case Type::RELOAD_DICTIONARY: - system_context.getExternalDictionaries().reloadDictionary(query->target_dictionary); + system_context.getExternalDictionaries().reloadDictionary(query.target_dictionary); break; case Type::RELOAD_DICTIONARIES: executeCommandsAndThrowIfError( @@ -171,38 +171,38 @@ BlockIO InterpreterSystemQuery::execute() system_context.reloadConfig(); break; case Type::STOP_MERGES: - startStopAction(context, *query, ActionLocks::PartsMerge, false); + startStopAction(context, query, ActionLocks::PartsMerge, false); break; case Type::START_MERGES: - startStopAction(context, *query, ActionLocks::PartsMerge, true); + startStopAction(context, query, ActionLocks::PartsMerge, true); break; case Type::STOP_FETCHES: - startStopAction(context, *query, ActionLocks::PartsFetch, false); + startStopAction(context, query, ActionLocks::PartsFetch, false); break; case Type::START_FETCHES: - startStopAction(context, *query, ActionLocks::PartsFetch, true); + startStopAction(context, query, ActionLocks::PartsFetch, true); break; case Type::STOP_REPLICATED_SENDS: - startStopAction(context, *query, ActionLocks::PartsSend, false); + startStopAction(context, query, ActionLocks::PartsSend, false); break; case Type::START_REPLICATED_SENDS: - startStopAction(context, *query, ActionLocks::PartsSend, true); + startStopAction(context, query, ActionLocks::PartsSend, true); break; case Type::STOP_REPLICATION_QUEUES: - startStopAction(context, *query, ActionLocks::ReplicationQueue, false); + startStopAction(context, query, ActionLocks::ReplicationQueue, false); break; case Type::START_REPLICATION_QUEUES: - startStopAction(context, *query, ActionLocks::ReplicationQueue, true); + startStopAction(context, query, ActionLocks::ReplicationQueue, true); break; case Type::SYNC_REPLICA: - syncReplica(*query); + syncReplica(query); break; case Type::RESTART_REPLICAS: restartReplicas(system_context); break; case Type::RESTART_REPLICA: - if (!tryRestartReplica(query->target_database, query->target_table, system_context)) - throw Exception("There is no " + query->target_database + "." + query->target_table + " replicated table", + if (!tryRestartReplica(query.target_database, query.target_table, system_context)) + throw Exception("There is no " + query.target_database + "." + query.target_table + " replicated table", ErrorCodes::BAD_ARGUMENTS); break; case Type::FLUSH_LOGS: @@ -214,7 +214,7 @@ BlockIO InterpreterSystemQuery::execute() break; case Type::STOP_LISTEN_QUERIES: case Type::START_LISTEN_QUERIES: - throw Exception(String(ASTSystemQuery::typeToString(query->type)) + " is not supported yet", ErrorCodes::NOT_IMPLEMENTED); + throw Exception(String(ASTSystemQuery::typeToString(query.type)) + " is not supported yet", ErrorCodes::NOT_IMPLEMENTED); default: throw Exception("Unknown type of SYSTEM query", ErrorCodes::BAD_ARGUMENTS); } @@ -248,20 +248,20 @@ StoragePtr InterpreterSystemQuery::tryRestartReplica(const String & database_nam /// Attach actions { /// getCreateTableQuery must return canonical CREATE query representation, there are no need for AST postprocessing - auto * create = create_ast->as(); - create->attach = true; + auto & create = create_ast->as(); + create.attach = true; std::string data_path = database->getDataPath(); - auto columns = InterpreterCreateQuery::getColumnsDescription(*create->columns_list->columns, system_context); + auto columns = InterpreterCreateQuery::getColumnsDescription(*create.columns_list->columns, system_context); - StoragePtr table = StorageFactory::instance().get(*create, + StoragePtr table = StorageFactory::instance().get(create, data_path, table_name, database_name, system_context, system_context.getGlobalContext(), columns, - create->attach, + create.attach, false); database->createTable(system_context, table_name, table, create_ast); diff --git a/dbms/src/Interpreters/InterpreterUseQuery.cpp b/dbms/src/Interpreters/InterpreterUseQuery.cpp index 2cd64ab985f..d815d66aadc 100644 --- a/dbms/src/Interpreters/InterpreterUseQuery.cpp +++ b/dbms/src/Interpreters/InterpreterUseQuery.cpp @@ -9,7 +9,7 @@ namespace DB BlockIO InterpreterUseQuery::execute() { - const String & new_database = query_ptr->as()->database; + const String & new_database = query_ptr->as().database; context.getSessionContext().setCurrentDatabase(new_database); return {}; } diff --git a/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp b/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp index d8c0a796cac..a99e79b1120 100644 --- a/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp +++ b/dbms/src/Interpreters/JoinToSubqueryTransformVisitor.cpp @@ -209,12 +209,12 @@ bool needRewrite(ASTSelectQuery & select) if (!table || !table->table_join) throw Exception("Multiple JOIN expects joined tables", ErrorCodes::LOGICAL_ERROR); - const auto * join = table->table_join->as(); - if (isComma(join->kind)) + const auto & join = table->table_join->as(); + if (isComma(join.kind)) throw Exception("COMMA to CROSS JOIN rewriter is not enabled or cannot rewrite query", ErrorCodes::NOT_IMPLEMENTED); /// it's not trivial to support mix of JOIN ON & JOIN USING cause of short names - if (join->using_expression_list) + if (join.using_expression_list) throw Exception("Multiple JOIN does not support USING", ErrorCodes::NOT_IMPLEMENTED); } @@ -263,9 +263,9 @@ void JoinToSubqueryTransformMatcher::visit(ASTSelectQuery & select, ASTPtr &, Da auto * table = child->as(); if (table->table_join) { - auto * join = table->table_join->as(); - if (join->on_expression) - ColumnAliasesVisitor(aliases_data).visit(join->on_expression); + auto & join = table->table_join->as(); + if (join.on_expression) + ColumnAliasesVisitor(aliases_data).visit(join.on_expression); } } diff --git a/dbms/src/Interpreters/QueryNormalizer.cpp b/dbms/src/Interpreters/QueryNormalizer.cpp index 2ca8e010e2f..f4f66f59dce 100644 --- a/dbms/src/Interpreters/QueryNormalizer.cpp +++ b/dbms/src/Interpreters/QueryNormalizer.cpp @@ -134,16 +134,16 @@ void QueryNormalizer::visit(ASTTablesInSelectQueryElement & node, const ASTPtr & /// mark table Identifiers as 'not a column' if (node.table_expression) { - auto * expr = node.table_expression->as(); - setIdentifierSpecial(expr->database_and_table_name); + auto & expr = node.table_expression->as(); + setIdentifierSpecial(expr.database_and_table_name); } /// normalize JOIN ON section if (node.table_join) { - auto * join = node.table_join->as(); - if (join->on_expression) - visit(join->on_expression, data); + auto & join = node.table_join->as(); + if (join.on_expression) + visit(join.on_expression, data); } } diff --git a/dbms/src/Interpreters/Set.cpp b/dbms/src/Interpreters/Set.cpp index 1eb97e3e0e3..c1cf279aee0 100644 --- a/dbms/src/Interpreters/Set.cpp +++ b/dbms/src/Interpreters/Set.cpp @@ -235,8 +235,8 @@ void Set::createFromAST(const DataTypes & types, ASTPtr node, const Context & co DataTypePtr tuple_type; Row tuple_values; - const auto * list = node->as(); - for (auto & elem : list->children) + const auto & list = node->as(); + for (auto & elem : list.children) { if (num_columns == 1) { diff --git a/dbms/src/Interpreters/SyntaxAnalyzer.cpp b/dbms/src/Interpreters/SyntaxAnalyzer.cpp index 4d887a352cc..aab7bd3d4c2 100644 --- a/dbms/src/Interpreters/SyntaxAnalyzer.cpp +++ b/dbms/src/Interpreters/SyntaxAnalyzer.cpp @@ -244,9 +244,9 @@ void optimizeGroupBy(ASTSelectQuery * select_query, const NameSet & source_colum continue; } - const auto & dict_name = function->arguments->children[0]->as()->value.safeGet(); + const auto & dict_name = function->arguments->children[0]->as().value.safeGet(); const auto & dict_ptr = context.getExternalDictionaries().getDictionary(dict_name); - const auto & attr_name = function->arguments->children[1]->as()->value.safeGet(); + const auto & attr_name = function->arguments->children[1]->as().value.safeGet(); if (!dict_ptr->isInjective(attr_name)) { @@ -324,9 +324,9 @@ void optimizeOrderBy(const ASTSelectQuery * select_query) for (const auto & elem : elems) { String name = elem->children.front()->getColumnName(); - const auto * order_by_elem = elem->as(); + const auto & order_by_elem = elem->as(); - if (elems_set.emplace(name, order_by_elem->collation ? order_by_elem->collation->getColumnName() : "").second) + if (elems_set.emplace(name, order_by_elem.collation ? order_by_elem.collation->getColumnName() : "").second) unique_elems.emplace_back(elem); } @@ -551,24 +551,24 @@ void collectJoinedColumns(AnalyzedJoin & analyzed_join, const ASTSelectQuery & s if (!node) return; - const auto * table_join = node->table_join->as(); - const auto * table_expression = node->table_expression->as(); - DatabaseAndTableWithAlias joined_table_name(*table_expression, current_database); + const auto & table_join = node->table_join->as(); + const auto & table_expression = node->table_expression->as(); + DatabaseAndTableWithAlias joined_table_name(table_expression, current_database); - if (table_join->using_expression_list) + if (table_join.using_expression_list) { - const auto * keys = table_join->using_expression_list->as(); - for (const auto & key : keys->children) + const auto & keys = table_join.using_expression_list->as(); + for (const auto & key : keys.children) analyzed_join.addUsingKey(key); for (auto & name : analyzed_join.key_names_right) if (source_columns.count(name)) name = joined_table_name.getQualifiedNamePrefix() + name; } - else if (table_join->on_expression) - collectJoinedColumnsFromJoinOnExpr(analyzed_join, *table_join); + else if (table_join.on_expression) + collectJoinedColumnsFromJoinOnExpr(analyzed_join, table_join); - bool make_nullable = join_use_nulls && isLeftOrFull(table_join->kind); + bool make_nullable = join_use_nulls && isLeftOrFull(table_join.kind); analyzed_join.calculateAvailableJoinedColumns(make_nullable); } @@ -593,19 +593,19 @@ void replaceJoinedTable(const ASTTablesInSelectQueryElement* join) if (!join || !join->table_expression) return; - const auto * table_expr = join->table_expression->as(); - if (table_expr->database_and_table_name) + auto & table_expr = join->table_expression->as(); + if (table_expr.database_and_table_name) { - const auto * table_id = table_expr->database_and_table_name->as(); - String expr = "(select * from " + table_id->name + ") as " + table_id->shortName(); + const auto & table_id = table_expr.database_and_table_name->as(); + String expr = "(select * from " + table_id.name + ") as " + table_id.shortName(); // FIXME: since the expression "a as b" exposes both "a" and "b" names, which is not equivalent to "(select * from a) as b", // we can't replace aliased tables. // FIXME: long table names include database name, which we can't save within alias. - if (table_id->alias.empty() && table_id->isShort()) + if (table_id.alias.empty() && table_id.isShort()) { ParserTableExpression parser; - table_expr = parseQuery(parser, expr, 0)->as(); + table_expr = parseQuery(parser, expr, 0)->as(); } } } @@ -650,10 +650,10 @@ SyntaxAnalyzerResultPtr SyntaxAnalyzer::analyze( if (settings.enable_optimize_predicate_expression) replaceJoinedTable(node); - const auto * joined_expression = node->table_expression->as(); - DatabaseAndTableWithAlias table(*joined_expression, context.getCurrentDatabase()); + const auto & joined_expression = node->table_expression->as(); + DatabaseAndTableWithAlias table(joined_expression, context.getCurrentDatabase()); - NamesAndTypesList joined_columns = getNamesAndTypeListFromTableExpression(*joined_expression, context); + NamesAndTypesList joined_columns = getNamesAndTypeListFromTableExpression(joined_expression, context); Names original_names = qualifyOccupiedNames(joined_columns, source_columns_set, table); result.analyzed_join.calculateColumnsFromJoinedTable(joined_columns, original_names); } diff --git a/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp b/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp index 5bfd2897c6c..47ab1528c65 100644 --- a/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp +++ b/dbms/src/Interpreters/TranslateQualifiedNamesVisitor.cpp @@ -237,12 +237,12 @@ void TranslateQualifiedNamesMatcher::visit(ASTExpressionList & node, const ASTPt /// 'select * from a join b using id' should result one 'id' column void TranslateQualifiedNamesMatcher::extractJoinUsingColumns(const ASTPtr ast, Data & data) { - const auto * table_join = ast->as(); + const auto & table_join = ast->as(); - if (table_join->using_expression_list) + if (table_join.using_expression_list) { - const auto * keys = table_join->using_expression_list->as(); - for (const auto & key : keys->children) + const auto & keys = table_join.using_expression_list->as(); + for (const auto & key : keys.children) if (auto opt_column = getIdentifierName(key)) data.join_using_columns.insert(*opt_column); else if (key->as()) diff --git a/dbms/src/Interpreters/executeQuery.cpp b/dbms/src/Interpreters/executeQuery.cpp index 2dd2066f4b1..56f515e91c8 100644 --- a/dbms/src/Interpreters/executeQuery.cpp +++ b/dbms/src/Interpreters/executeQuery.cpp @@ -498,7 +498,7 @@ void executeQuery( if (!allow_into_outfile) throw Exception("INTO OUTFILE is not allowed", ErrorCodes::INTO_OUTFILE_NOT_ALLOWED); - const auto & out_file = ast_query_with_output->out_file->as()->value.safeGet(); + const auto & out_file = ast_query_with_output->out_file->as().value.safeGet(); out_file_buf.emplace(out_file, DBMS_DEFAULT_BUFFER_SIZE, O_WRONLY | O_EXCL | O_CREAT); out_buf = &*out_file_buf; } diff --git a/dbms/src/Interpreters/loadMetadata.cpp b/dbms/src/Interpreters/loadMetadata.cpp index 334fd5bb490..e0caa8f433d 100644 --- a/dbms/src/Interpreters/loadMetadata.cpp +++ b/dbms/src/Interpreters/loadMetadata.cpp @@ -39,9 +39,9 @@ static void executeCreateQuery( ParserCreateQuery parser; ASTPtr ast = parseQuery(parser, query.data(), query.data() + query.size(), "in file " + file_name, 0); - auto * ast_create_query = ast->as(); - ast_create_query->attach = true; - ast_create_query->database = database; + auto & ast_create_query = ast->as(); + ast_create_query.attach = true; + ast_create_query.database = database; InterpreterCreateQuery interpreter(ast, context); interpreter.setInternal(true); diff --git a/dbms/src/Parsers/ASTRenameQuery.h b/dbms/src/Parsers/ASTRenameQuery.h index b0deb97a145..1666873ed9c 100644 --- a/dbms/src/Parsers/ASTRenameQuery.h +++ b/dbms/src/Parsers/ASTRenameQuery.h @@ -41,10 +41,10 @@ public: ASTPtr getRewrittenASTWithoutOnCluster(const std::string & new_database) const override { auto query_ptr = clone(); - auto * query = query_ptr->as(); + auto & query = query_ptr->as(); - query->cluster.clear(); - for (Element & elem : query->elements) + query.cluster.clear(); + for (Element & elem : query.elements) { if (elem.from.database.empty()) elem.from.database = new_database; diff --git a/dbms/src/Parsers/ASTSelectQuery.cpp b/dbms/src/Parsers/ASTSelectQuery.cpp index b3b94335889..b7ad77ba48d 100644 --- a/dbms/src/Parsers/ASTSelectQuery.cpp +++ b/dbms/src/Parsers/ASTSelectQuery.cpp @@ -65,7 +65,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << indent_str << "WITH " << (s.hilite ? hilite_none : ""); s.one_line ? with_expression_list->formatImpl(s, state, frame) - : with_expression_list->as()->formatImplMultiline(s, state, frame); + : with_expression_list->as().formatImplMultiline(s, state, frame); s.ostr << s.nl_or_ws; } @@ -73,7 +73,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.one_line ? select_expression_list->formatImpl(s, state, frame) - : select_expression_list->as()->formatImplMultiline(s, state, frame); + : select_expression_list->as().formatImplMultiline(s, state, frame); if (tables) { @@ -98,7 +98,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << s.nl_or_ws << indent_str << "GROUP BY " << (s.hilite ? hilite_none : ""); s.one_line ? group_expression_list->formatImpl(s, state, frame) - : group_expression_list->as()->formatImplMultiline(s, state, frame); + : group_expression_list->as().formatImplMultiline(s, state, frame); } if (group_by_with_rollup) @@ -121,7 +121,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << s.nl_or_ws << indent_str << "ORDER BY " << (s.hilite ? hilite_none : ""); s.one_line ? order_expression_list->formatImpl(s, state, frame) - : order_expression_list->as()->formatImplMultiline(s, state, frame); + : order_expression_list->as().formatImplMultiline(s, state, frame); } if (limit_by_value) @@ -131,7 +131,7 @@ void ASTSelectQuery::formatImpl(const FormatSettings & s, FormatState & state, F s.ostr << (s.hilite ? hilite_keyword : "") << " BY " << (s.hilite ? hilite_none : ""); s.one_line ? limit_by_expression_list->formatImpl(s, state, frame) - : limit_by_expression_list->as()->formatImplMultiline(s, state, frame); + : limit_by_expression_list->as().formatImplMultiline(s, state, frame); } if (limit_length) @@ -161,15 +161,15 @@ static const ASTTableExpression * getFirstTableExpression(const ASTSelectQuery & if (!select.tables) return {}; - const auto * tables_in_select_query = select.tables->as(); - if (tables_in_select_query->children.empty()) + const auto & tables_in_select_query = select.tables->as(); + if (tables_in_select_query.children.empty()) return {}; - const auto * tables_element = tables_in_select_query->children[0]->as(); - if (!tables_element->table_expression) + const auto & tables_element = tables_in_select_query.children[0]->as(); + if (!tables_element.table_expression) return {}; - return tables_element->table_expression->as(); + return tables_element.table_expression->as(); } static ASTTableExpression * getFirstTableExpression(ASTSelectQuery & select) @@ -177,15 +177,15 @@ static ASTTableExpression * getFirstTableExpression(ASTSelectQuery & select) if (!select.tables) return {}; - auto * tables_in_select_query = select.tables->as(); - if (tables_in_select_query->children.empty()) + auto & tables_in_select_query = select.tables->as(); + if (tables_in_select_query.children.empty()) return {}; - auto * tables_element = tables_in_select_query->children[0]->as(); - if (!tables_element->table_expression) + auto & tables_element = tables_in_select_query.children[0]->as(); + if (!tables_element.table_expression) return {}; - return tables_element->table_expression->as(); + return tables_element.table_expression->as(); } static const ASTArrayJoin * getFirstArrayJoin(const ASTSelectQuery & select) @@ -193,18 +193,18 @@ static const ASTArrayJoin * getFirstArrayJoin(const ASTSelectQuery & select) if (!select.tables) return {}; - const auto * tables_in_select_query = select.tables->as(); - if (tables_in_select_query->children.empty()) + const auto & tables_in_select_query = select.tables->as(); + if (tables_in_select_query.children.empty()) return {}; const ASTArrayJoin * array_join = nullptr; - for (const auto & child : tables_in_select_query->children) + for (const auto & child : tables_in_select_query.children) { - const auto * tables_element = child->as(); - if (tables_element->array_join) + const auto & tables_element = child->as(); + if (tables_element.array_join) { if (!array_join) - array_join = tables_element->array_join->as(); + array_join = tables_element.array_join->as(); else throw Exception("Support for more than one ARRAY JOIN in query is not implemented", ErrorCodes::NOT_IMPLEMENTED); } @@ -218,18 +218,18 @@ static const ASTTablesInSelectQueryElement * getFirstTableJoin(const ASTSelectQu if (!select.tables) return {}; - const auto * tables_in_select_query = select.tables->as(); - if (tables_in_select_query->children.empty()) + const auto & tables_in_select_query = select.tables->as(); + if (tables_in_select_query.children.empty()) return {}; const ASTTablesInSelectQueryElement * joined_table = nullptr; - for (const auto & child : tables_in_select_query->children) + for (const auto & child : tables_in_select_query.children) { - const auto * tables_element = child->as(); - if (tables_element->table_join) + const auto & tables_element = child->as(); + if (tables_element.table_join) { if (!joined_table) - joined_table = tables_element; + joined_table = &tables_element; else throw Exception("Multiple JOIN disabled or does not support the query. " "'set allow_experimental_multiple_joins_emulation' to enable.", ErrorCodes::NOT_IMPLEMENTED); diff --git a/dbms/src/Parsers/ASTTablesInSelectQuery.cpp b/dbms/src/Parsers/ASTTablesInSelectQuery.cpp index da8ae0a4a2d..fb278046377 100644 --- a/dbms/src/Parsers/ASTTablesInSelectQuery.cpp +++ b/dbms/src/Parsers/ASTTablesInSelectQuery.cpp @@ -208,7 +208,7 @@ void ASTArrayJoin::formatImpl(const FormatSettings & settings, FormatState & sta settings.one_line ? expression_list->formatImpl(settings, state, frame) - : expression_list->as()->formatImplMultiline(settings, state, frame); + : expression_list->as().formatImplMultiline(settings, state, frame); } @@ -218,7 +218,7 @@ void ASTTablesInSelectQueryElement::formatImpl(const FormatSettings & settings, { if (table_join) { - table_join->as()->formatImplBeforeTable(settings, state, frame); + table_join->as().formatImplBeforeTable(settings, state, frame); settings.ostr << " "; } @@ -226,7 +226,7 @@ void ASTTablesInSelectQueryElement::formatImpl(const FormatSettings & settings, settings.ostr << " "; if (table_join) - table_join->as()->formatImplAfterTable(settings, state, frame); + table_join->as().formatImplAfterTable(settings, state, frame); } else if (array_join) { diff --git a/dbms/src/Parsers/ExpressionElementParsers.cpp b/dbms/src/Parsers/ExpressionElementParsers.cpp index 9df7c0a05a4..4cde7219fdb 100644 --- a/dbms/src/Parsers/ExpressionElementParsers.cpp +++ b/dbms/src/Parsers/ExpressionElementParsers.cpp @@ -82,18 +82,18 @@ bool ParserParenthesisExpression::parseImpl(Pos & pos, ASTPtr & node, Expected & return false; ++pos; - const auto * expr_list = contents_node->as(); + const auto & expr_list = contents_node->as(); /// empty expression in parentheses is not allowed - if (expr_list->children.empty()) + if (expr_list.children.empty()) { expected.add(pos, "non-empty parenthesized list of expressions"); return false; } - if (expr_list->children.size() == 1) + if (expr_list.children.size() == 1) { - node = expr_list->children.front(); + node = expr_list.children.front(); } else { @@ -170,8 +170,8 @@ bool ParserCompoundIdentifier::parseImpl(Pos & pos, ASTPtr & node, Expected & ex String name; std::vector parts; - const auto * list = id_list->as(); - for (const auto & child : list->children) + const auto & list = id_list->as(); + for (const auto & child : list.children) { if (!name.empty()) name += '.'; @@ -1075,7 +1075,7 @@ bool ParserArrayOfLiterals::parseImpl(Pos & pos, ASTPtr & node, Expected & expec if (!literal_p.parse(pos, literal_node, expected)) return false; - arr.push_back(literal_node->as()->value); + arr.push_back(literal_node->as().value); } expected.add(pos, "closing square bracket"); diff --git a/dbms/src/Parsers/ExpressionListParsers.cpp b/dbms/src/Parsers/ExpressionListParsers.cpp index 9fc72c4520e..b948a22ce2a 100644 --- a/dbms/src/Parsers/ExpressionListParsers.cpp +++ b/dbms/src/Parsers/ExpressionListParsers.cpp @@ -213,7 +213,7 @@ bool ParserVariableArityOperatorList::parseImpl(Pos & pos, ASTPtr & node, Expect if (!arguments) { node = makeASTFunction(function_name, node); - arguments = node->as()->arguments; + arguments = node->as().arguments; } ASTPtr elem; diff --git a/dbms/src/Parsers/ParserAlterQuery.cpp b/dbms/src/Parsers/ParserAlterQuery.cpp index 70d84fea111..b33679ad26b 100644 --- a/dbms/src/Parsers/ParserAlterQuery.cpp +++ b/dbms/src/Parsers/ParserAlterQuery.cpp @@ -202,7 +202,7 @@ bool ParserAlterCommand::parseImpl(Pos & pos, ASTPtr & node, Expected & expected if (!parser_string_literal.parse(pos, ast_from, expected)) return false; - command->from = ast_from->as()->value.get(); + command->from = ast_from->as().value.get(); command->type = ASTAlterCommand::FETCH_PARTITION; } else if (s_freeze.ignore(pos, expected)) @@ -229,7 +229,7 @@ bool ParserAlterCommand::parseImpl(Pos & pos, ASTPtr & node, Expected & expected if (!parser_string_literal.parse(pos, ast_with_name, expected)) return false; - command->with_name = ast_with_name->as()->value.get(); + command->with_name = ast_with_name->as().value.get(); } } else if (s_modify_column.ignore(pos, expected)) diff --git a/dbms/src/Parsers/ParserCreateQuery.cpp b/dbms/src/Parsers/ParserCreateQuery.cpp index 63bee94c90c..72610951868 100644 --- a/dbms/src/Parsers/ParserCreateQuery.cpp +++ b/dbms/src/Parsers/ParserCreateQuery.cpp @@ -126,8 +126,8 @@ bool ParserIndexDeclaration::parseImpl(Pos & pos, ASTPtr & node, Expected & expe return false; auto index = std::make_shared(); - index->name = name->as()->name; - index->granularity = granularity->as()->value.get(); + index->name = name->as().name; + index->granularity = granularity->as().value.get(); index->set(index->expr, expr); index->set(index->type, type); node = index; diff --git a/dbms/src/Parsers/ParserPartition.cpp b/dbms/src/Parsers/ParserPartition.cpp index d2405cb81c8..6d2c259f8bf 100644 --- a/dbms/src/Parsers/ParserPartition.cpp +++ b/dbms/src/Parsers/ParserPartition.cpp @@ -26,7 +26,7 @@ bool ParserPartition::parseImpl(Pos & pos, ASTPtr & node, Expected & expected) if (!parser_string_literal.parse(pos, partition_id, expected)) return false; - partition->id = partition_id->as()->value.get(); + partition->id = partition_id->as().value.get(); } else { diff --git a/dbms/src/Parsers/ParserQueryWithOutput.cpp b/dbms/src/Parsers/ParserQueryWithOutput.cpp index 0ee67dab9c9..c41e0946a96 100644 --- a/dbms/src/Parsers/ParserQueryWithOutput.cpp +++ b/dbms/src/Parsers/ParserQueryWithOutput.cpp @@ -63,16 +63,16 @@ bool ParserQueryWithOutput::parseImpl(Pos & pos, ASTPtr & node, Expected & expec return false; /// FIXME: try to prettify this cast using `as<>()` - auto * query_with_output = dynamic_cast(query.get()); + auto & query_with_output = dynamic_cast(*query); ParserKeyword s_into_outfile("INTO OUTFILE"); if (s_into_outfile.ignore(pos, expected)) { ParserStringLiteral out_file_p; - if (!out_file_p.parse(pos, query_with_output->out_file, expected)) + if (!out_file_p.parse(pos, query_with_output.out_file, expected)) return false; - query_with_output->children.push_back(query_with_output->out_file); + query_with_output.children.push_back(query_with_output.out_file); } ParserKeyword s_format("FORMAT"); @@ -81,11 +81,11 @@ bool ParserQueryWithOutput::parseImpl(Pos & pos, ASTPtr & node, Expected & expec { ParserIdentifier format_p; - if (!format_p.parse(pos, query_with_output->format, expected)) + if (!format_p.parse(pos, query_with_output.format, expected)) return false; - setIdentifierSpecial(query_with_output->format); + setIdentifierSpecial(query_with_output.format); - query_with_output->children.push_back(query_with_output->format); + query_with_output.children.push_back(query_with_output.format); } // SETTINGS key1 = value1, key2 = value2, ... @@ -93,9 +93,9 @@ bool ParserQueryWithOutput::parseImpl(Pos & pos, ASTPtr & node, Expected & expec if (s_settings.ignore(pos, expected)) { ParserSetQuery parser_settings(true); - if (!parser_settings.parse(pos, query_with_output->settings_ast, expected)) + if (!parser_settings.parse(pos, query_with_output.settings_ast, expected)) return false; - query_with_output->children.push_back(query_with_output->settings_ast); + query_with_output.children.push_back(query_with_output.settings_ast); } if (explain_ast) diff --git a/dbms/src/Parsers/ParserSetQuery.cpp b/dbms/src/Parsers/ParserSetQuery.cpp index 25ca6877246..9eb94a76364 100644 --- a/dbms/src/Parsers/ParserSetQuery.cpp +++ b/dbms/src/Parsers/ParserSetQuery.cpp @@ -32,7 +32,7 @@ static bool parseNameValuePair(ASTSetQuery::Change & change, IParser::Pos & pos, return false; getIdentifierName(name, change.name); - change.value = value->as()->value; + change.value = value->as().value; return true; } diff --git a/dbms/src/Parsers/ParserShowTablesQuery.cpp b/dbms/src/Parsers/ParserShowTablesQuery.cpp index 1fb9ea9bab7..9c247a284c1 100644 --- a/dbms/src/Parsers/ParserShowTablesQuery.cpp +++ b/dbms/src/Parsers/ParserShowTablesQuery.cpp @@ -67,7 +67,7 @@ bool ParserShowTablesQuery::parseImpl(Pos & pos, ASTPtr & node, Expected & expec getIdentifierName(database, query->from); if (like) - query->like = safeGet(like->as()->value); + query->like = safeGet(like->as().value); node = query; diff --git a/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp b/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp index 70936dfe0e0..815a5d3f3cc 100644 --- a/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp +++ b/dbms/src/Parsers/parseIdentifierOrStringLiteral.cpp @@ -17,7 +17,7 @@ bool parseIdentifierOrStringLiteral(IParser::Pos & pos, Expected & expected, Str if (!ParserStringLiteral().parse(pos, res, expected)) return false; - result = res->as()->value.safeGet(); + result = res->as().value.safeGet(); } else result = *getIdentifierName(res); diff --git a/dbms/src/Storages/AlterCommands.cpp b/dbms/src/Storages/AlterCommands.cpp index 048373969ff..27126b7bcdf 100644 --- a/dbms/src/Storages/AlterCommands.cpp +++ b/dbms/src/Storages/AlterCommands.cpp @@ -39,21 +39,21 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = AlterCommand::ADD_COLUMN; - const auto * ast_col_decl = command_ast->col_decl->as(); + const auto & ast_col_decl = command_ast->col_decl->as(); - command.column_name = ast_col_decl->name; - if (ast_col_decl->type) + command.column_name = ast_col_decl.name; + if (ast_col_decl.type) { - command.data_type = data_type_factory.get(ast_col_decl->type); + command.data_type = data_type_factory.get(ast_col_decl.type); } - if (ast_col_decl->default_expression) + if (ast_col_decl.default_expression) { - command.default_kind = columnDefaultKindFromString(ast_col_decl->default_specifier); - command.default_expression = ast_col_decl->default_expression; + command.default_kind = columnDefaultKindFromString(ast_col_decl.default_specifier); + command.default_expression = ast_col_decl.default_expression; } - if (ast_col_decl->codec) - command.codec = compression_codec_factory.get(ast_col_decl->codec); + if (ast_col_decl.codec) + command.codec = compression_codec_factory.get(ast_col_decl.codec); if (command_ast->column) command.after_column = *getIdentifierName(command_ast->column); @@ -78,27 +78,27 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = AlterCommand::MODIFY_COLUMN; - const auto * ast_col_decl = command_ast->col_decl->as(); + const auto & ast_col_decl = command_ast->col_decl->as(); - command.column_name = ast_col_decl->name; - if (ast_col_decl->type) + command.column_name = ast_col_decl.name; + if (ast_col_decl.type) { - command.data_type = data_type_factory.get(ast_col_decl->type); + command.data_type = data_type_factory.get(ast_col_decl.type); } - if (ast_col_decl->default_expression) + if (ast_col_decl.default_expression) { - command.default_kind = columnDefaultKindFromString(ast_col_decl->default_specifier); - command.default_expression = ast_col_decl->default_expression; + command.default_kind = columnDefaultKindFromString(ast_col_decl.default_specifier); + command.default_expression = ast_col_decl.default_expression; } - if (ast_col_decl->codec) - command.codec = compression_codec_factory.get(ast_col_decl->codec); + if (ast_col_decl.codec) + command.codec = compression_codec_factory.get(ast_col_decl.codec); - if (ast_col_decl->comment) + if (ast_col_decl.comment) { - const auto * ast_comment = ast_col_decl->comment->as(); - command.comment = ast_comment->value.get(); + const auto & ast_comment = ast_col_decl.comment->as(); + command.comment = ast_comment.value.get(); } command.if_exists = command_ast->if_exists; @@ -109,8 +109,8 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = COMMENT_COLUMN; command.column_name = *getIdentifierName(command_ast->column); - const auto * ast_comment = command_ast->comment->as(); - command.comment = ast_comment->value.get(); + const auto & ast_comment = command_ast->comment->as(); + command.comment = ast_comment.value.get(); command.if_exists = command_ast->if_exists; return command; } @@ -127,12 +127,12 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ command.index_decl = command_ast->index_decl; command.type = AlterCommand::ADD_INDEX; - const auto * ast_index_decl = command_ast->index_decl->as(); + const auto & ast_index_decl = command_ast->index_decl->as(); - command.index_name = ast_index_decl->name; + command.index_name = ast_index_decl.name; if (command_ast->index) - command.after_index_name = command_ast->index->as()->name; + command.after_index_name = command_ast->index->as().name; command.if_not_exists = command_ast->if_not_exists; @@ -145,7 +145,7 @@ std::optional AlterCommand::parse(const ASTAlterCommand * command_ AlterCommand command; command.type = AlterCommand::DROP_INDEX; - command.index_name = command_ast->index->as()->name; + command.index_name = command_ast->index->as().name; command.if_exists = command_ast->if_exists; return command; @@ -335,7 +335,7 @@ void AlterCommand::apply(ColumnsDescription & columns_description, IndicesDescri indices_description.indices.cend(), [this](const ASTPtr & index_ast) { - return index_ast->as()->name == index_name; + return index_ast->as().name == index_name; })) { if (if_not_exists) @@ -354,7 +354,7 @@ void AlterCommand::apply(ColumnsDescription & columns_description, IndicesDescri indices_description.indices.end(), [this](const ASTPtr & index_ast) { - return index_ast->as()->name == after_index_name; + return index_ast->as().name == after_index_name; }); if (insert_it == indices_description.indices.end()) @@ -373,7 +373,7 @@ void AlterCommand::apply(ColumnsDescription & columns_description, IndicesDescri indices_description.indices.end(), [this](const ASTPtr & index_ast) { - return index_ast->as()->name == index_name; + return index_ast->as().name == index_name; }); if (erase_it == indices_description.indices.end()) diff --git a/dbms/src/Storages/ColumnsDescription.cpp b/dbms/src/Storages/ColumnsDescription.cpp index 0a7e8f4abc5..0f0636bc47f 100644 --- a/dbms/src/Storages/ColumnsDescription.cpp +++ b/dbms/src/Storages/ColumnsDescription.cpp @@ -185,7 +185,7 @@ void parseColumn(ReadBufferFromString & buf, ColumnsDescription & result, const result.ordinary.emplace_back(column_name, std::move(type)); if (col_ast->comment) - if (auto comment_str = col_ast->comment->as()->value.get(); !comment_str.empty()) + if (auto comment_str = col_ast->comment->as().value.get(); !comment_str.empty()) result.comments.emplace(column_name, std::move(comment_str)); if (col_ast->codec) diff --git a/dbms/src/Storages/Kafka/StorageKafka.cpp b/dbms/src/Storages/Kafka/StorageKafka.cpp index a5917d1fd98..5785e65d4d9 100644 --- a/dbms/src/Storages/Kafka/StorageKafka.cpp +++ b/dbms/src/Storages/Kafka/StorageKafka.cpp @@ -429,7 +429,7 @@ void registerStorageKafka(StorageFactory & factory) if (args_count >= 2) { engine_args[1] = evaluateConstantExpressionAsLiteral(engine_args[1], args.local_context); - topic_list = engine_args[1]->as()->value.safeGet(); + topic_list = engine_args[1]->as().value.safeGet(); } else if (kafka_settings.kafka_topic_list.changed) { @@ -447,7 +447,7 @@ void registerStorageKafka(StorageFactory & factory) if (args_count >= 3) { engine_args[2] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[2], args.local_context); - group = engine_args[2]->as()->value.safeGet(); + group = engine_args[2]->as().value.safeGet(); } else if (kafka_settings.kafka_group_name.changed) { diff --git a/dbms/src/Storages/MergeTree/KeyCondition.cpp b/dbms/src/Storages/MergeTree/KeyCondition.cpp index c30d8da6fb1..61ae85549c9 100644 --- a/dbms/src/Storages/MergeTree/KeyCondition.cpp +++ b/dbms/src/Storages/MergeTree/KeyCondition.cpp @@ -284,20 +284,20 @@ KeyCondition::KeyCondition( Block block_with_constants = getBlockWithConstants(query_info.query, query_info.syntax_analyzer_result, context); /// Trasform WHERE section to Reverse Polish notation - const auto * select = query_info.query->as(); - if (select->where_expression) + const auto & select = query_info.query->as(); + if (select.where_expression) { - traverseAST(select->where_expression, context, block_with_constants); + traverseAST(select.where_expression, context, block_with_constants); - if (select->prewhere_expression) + if (select.prewhere_expression) { - traverseAST(select->prewhere_expression, context, block_with_constants); + traverseAST(select.prewhere_expression, context, block_with_constants); rpn.emplace_back(RPNElement::FUNCTION_AND); } } - else if (select->prewhere_expression) + else if (select.prewhere_expression) { - traverseAST(select->prewhere_expression, context, block_with_constants); + traverseAST(select.prewhere_expression, context, block_with_constants); } else { @@ -622,7 +622,7 @@ bool KeyCondition::atomFromAST(const ASTPtr & node, const Context & context, Blo DataTypePtr const_type; if (const auto * func = node->as()) { - const ASTs & args = func->arguments->as()->children; + const ASTs & args = func->arguments->children; if (args.size() != 2) return false; diff --git a/dbms/src/Storages/MergeTree/MergeTreeData.cpp b/dbms/src/Storages/MergeTree/MergeTreeData.cpp index e671870b133..adc83bc338b 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeData.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeData.cpp @@ -1174,14 +1174,14 @@ void MergeTreeData::createConvertExpression(const DataPartPtr & part, const Name /// Remove old indices std::set new_indices_set; for (const auto & index_decl : new_indices) - new_indices_set.emplace(index_decl->as()->name); + new_indices_set.emplace(index_decl->as().name); for (const auto & index_decl : old_indices) { - const auto * index = index_decl->as(); - if (!new_indices_set.count(index->name)) + const auto & index = index_decl->as(); + if (!new_indices_set.count(index.name)) { - out_rename_map["skp_idx_" + index->name + ".idx"] = ""; - out_rename_map["skp_idx_" + index->name + ".mrk"] = ""; + out_rename_map["skp_idx_" + index.name + ".idx"] = ""; + out_rename_map["skp_idx_" + index.name + ".mrk"] = ""; } } @@ -2220,7 +2220,7 @@ void MergeTreeData::freezePartition(const ASTPtr & partition_ast, const String & if (format_version < MERGE_TREE_DATA_MIN_FORMAT_VERSION_WITH_CUSTOM_PARTITIONING) { /// Month-partitioning specific - partition value can represent a prefix of the partition to freeze. - if (const auto * partition_lit = partition_ast->as()->value->as()) + if (const auto * partition_lit = partition_ast->as().value->as()) prefix = partition_lit->value.getType() == Field::Types::UInt64 ? toString(partition_lit->value.get()) : partition_lit->value.safeGet(); @@ -2275,15 +2275,15 @@ size_t MergeTreeData::getPartitionSize(const std::string & partition_id) const String MergeTreeData::getPartitionIDFromQuery(const ASTPtr & ast, const Context & context) { - const auto * partition_ast = ast->as(); + const auto & partition_ast = ast->as(); - if (!partition_ast->value) - return partition_ast->id; + if (!partition_ast.value) + return partition_ast.id; if (format_version < MERGE_TREE_DATA_MIN_FORMAT_VERSION_WITH_CUSTOM_PARTITIONING) { /// Month-partitioning specific - partition ID can be passed in the partition value. - const auto * partition_lit = partition_ast->value->as(); + const auto * partition_lit = partition_ast.value->as(); if (partition_lit && partition_lit->value.getType() == Field::Types::String) { String partition_id = partition_lit->value.get(); @@ -2298,9 +2298,9 @@ String MergeTreeData::getPartitionIDFromQuery(const ASTPtr & ast, const Context /// Re-parse partition key fields using the information about expected field types. size_t fields_count = partition_key_sample.columns(); - if (partition_ast->fields_count != fields_count) + if (partition_ast.fields_count != fields_count) throw Exception( - "Wrong number of fields in the partition expression: " + toString(partition_ast->fields_count) + + "Wrong number of fields in the partition expression: " + toString(partition_ast.fields_count) + ", must be: " + toString(fields_count), ErrorCodes::INVALID_PARTITION_VALUE); @@ -2310,7 +2310,7 @@ String MergeTreeData::getPartitionIDFromQuery(const ASTPtr & ast, const Context if (fields_count) { ReadBufferFromMemory left_paren_buf("(", 1); - ReadBufferFromMemory fields_buf(partition_ast->fields_str.data, partition_ast->fields_str.size); + ReadBufferFromMemory fields_buf(partition_ast.fields_str.data, partition_ast.fields_str.size); ReadBufferFromMemory right_paren_buf(")", 1); ConcatReadBuffer buf({&left_paren_buf, &fields_buf, &right_paren_buf}); @@ -2320,7 +2320,7 @@ String MergeTreeData::getPartitionIDFromQuery(const ASTPtr & ast, const Context RowReadExtension unused; if (!input_stream.read(columns, unused)) throw Exception( - "Could not parse partition value: `" + partition_ast->fields_str.toString() + "`", + "Could not parse partition value: `" + partition_ast.fields_str.toString() + "`", ErrorCodes::INVALID_PARTITION_VALUE); for (size_t i = 0; i < fields_count; ++i) diff --git a/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp b/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp index 67df82e83e1..3f8c3aa3006 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeDataSelectExecutor.cpp @@ -129,9 +129,9 @@ static RelativeSize convertAbsoluteSampleSizeToRelative(const ASTPtr & node, siz if (approx_total_rows == 0) return 1; - const auto * node_sample = node->as(); + const auto & node_sample = node->as(); - auto absolute_sample_size = node_sample->ratio.numerator / node_sample->ratio.denominator; + auto absolute_sample_size = node_sample.ratio.numerator / node_sample.ratio.denominator; return std::min(RelativeSize(1), RelativeSize(absolute_sample_size) / RelativeSize(approx_total_rows)); } @@ -287,16 +287,16 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( RelativeSize relative_sample_size = 0; RelativeSize relative_sample_offset = 0; - const auto * select = query_info.query->as(); + const auto & select = query_info.query->as(); - auto select_sample_size = select->sample_size(); - auto select_sample_offset = select->sample_offset(); + auto select_sample_size = select.sample_size(); + auto select_sample_offset = select.sample_offset(); if (select_sample_size) { relative_sample_size.assign( - select_sample_size->as()->ratio.numerator, - select_sample_size->as()->ratio.denominator); + select_sample_size->as().ratio.numerator, + select_sample_size->as().ratio.denominator); if (relative_sample_size < 0) throw Exception("Negative sample size", ErrorCodes::ARGUMENT_OUT_OF_BOUND); @@ -304,8 +304,8 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( relative_sample_offset = 0; if (select_sample_offset) relative_sample_offset.assign( - select_sample_offset->as()->ratio.numerator, - select_sample_offset->as()->ratio.denominator); + select_sample_offset->as().ratio.numerator, + select_sample_offset->as().ratio.denominator); if (relative_sample_offset < 0) throw Exception("Negative sample offset", ErrorCodes::ARGUMENT_OUT_OF_BOUND); @@ -512,8 +512,8 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( /// PREWHERE String prewhere_column; - if (select->prewhere_expression) - prewhere_column = select->prewhere_expression->getColumnName(); + if (select.prewhere_expression) + prewhere_column = select.prewhere_expression->getColumnName(); RangesInDataParts parts_with_ranges; @@ -563,7 +563,7 @@ BlockInputStreams MergeTreeDataSelectExecutor::readFromParts( BlockInputStreams res; - if (select->final()) + if (select.final()) { /// Add columns needed to calculate the sorting expression and the sign. std::vector add_columns = data.sorting_key_expr->getRequiredColumns(); diff --git a/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp b/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp index 089dc3ed8f3..9a014676a1f 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeSetSkippingIndex.cpp @@ -225,19 +225,19 @@ SetIndexCondition::SetIndexCondition( key_columns.insert(name); } - const auto * select = query.query->as(); + const auto & select = query.query->as(); /// Replace logical functions with bit functions. /// Working with UInt8: last bit = can be true, previous = can be false. - if (select->where_expression && select->prewhere_expression) + if (select.where_expression && select.prewhere_expression) expression_ast = makeASTFunction( "and", - select->where_expression->clone(), - select->prewhere_expression->clone()); - else if (select->where_expression) - expression_ast = select->where_expression->clone(); - else if (select->prewhere_expression) - expression_ast = select->prewhere_expression->clone(); + select.where_expression->clone(), + select.prewhere_expression->clone()); + else if (select.where_expression) + expression_ast = select.where_expression->clone(); + else if (select.prewhere_expression) + expression_ast = select.prewhere_expression->clone(); else expression_ast = std::make_shared(UNKNOWN_FIELD); @@ -475,7 +475,7 @@ std::unique_ptr setIndexCreator( if (!node->type->arguments || node->type->arguments->children.size() != 1) throw Exception("Set index must have exactly one argument.", ErrorCodes::INCORRECT_QUERY); else if (node->type->arguments->children.size() == 1) - max_rows = node->type->arguments->children[0]->as()->value.get(); + max_rows = node->type->arguments->children[0]->as().value.get(); ASTPtr expr_list = MergeTreeData::extractKeyExpressionList(node->expr->clone()); diff --git a/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp b/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp index ac43508ae42..fc0b13ebbc0 100644 --- a/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp +++ b/dbms/src/Storages/MergeTree/MergeTreeWhereOptimizer.cpp @@ -44,8 +44,8 @@ MergeTreeWhereOptimizer::MergeTreeWhereOptimizer( first_primary_key_column = data.primary_key_columns[0]; calculateColumnSizes(data, queried_columns); - determineArrayJoinedNames(*query_info.query->as()); - optimize(*query_info.query->as()); + determineArrayJoinedNames(query_info.query->as()); + optimize(query_info.query->as()); } diff --git a/dbms/src/Storages/MutationCommands.cpp b/dbms/src/Storages/MutationCommands.cpp index 5e85a597150..349ecb66980 100644 --- a/dbms/src/Storages/MutationCommands.cpp +++ b/dbms/src/Storages/MutationCommands.cpp @@ -35,10 +35,10 @@ std::optional MutationCommand::parse(ASTAlterCommand * command) res.predicate = command->predicate; for (const ASTPtr & assignment_ast : command->update_assignments->children) { - const auto * assignment = assignment_ast->as(); - auto insertion = res.column_to_update_expression.emplace(assignment->column_name, assignment->expression); + const auto & assignment = assignment_ast->as(); + auto insertion = res.column_to_update_expression.emplace(assignment.column_name, assignment.expression); if (!insertion.second) - throw Exception("Multiple assignments in the single statement to column `" + assignment->column_name + "`", + throw Exception("Multiple assignments in the single statement to column `" + assignment.column_name + "`", ErrorCodes::MULTIPLE_ASSIGNMENTS_TO_COLUMN); } return res; @@ -71,7 +71,7 @@ void MutationCommands::readText(ReadBuffer & in) ParserAlterCommandList p_alter_commands; auto commands_ast = parseQuery( p_alter_commands, commands_str.data(), commands_str.data() + commands_str.length(), "mutation commands list", 0); - for (ASTAlterCommand * command_ast : commands_ast->as()->commands) + for (ASTAlterCommand * command_ast : commands_ast->as().commands) { auto command = MutationCommand::parse(command_ast); if (!command) diff --git a/dbms/src/TableFunctions/TableFunctionMerge.cpp b/dbms/src/TableFunctions/TableFunctionMerge.cpp index eda2720a7bc..9dfd94b6512 100644 --- a/dbms/src/TableFunctions/TableFunctionMerge.cpp +++ b/dbms/src/TableFunctions/TableFunctionMerge.cpp @@ -73,8 +73,8 @@ StoragePtr TableFunctionMerge::executeImpl(const ASTPtr & ast_function, const Co args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(args[0], context); args[1] = evaluateConstantExpressionAsLiteral(args[1], context); - String source_database = args[0]->as()->value.safeGet(); - String table_name_regexp = args[1]->as()->value.safeGet(); + String source_database = args[0]->as().value.safeGet(); + String table_name_regexp = args[1]->as().value.safeGet(); auto res = StorageMerge::create( getName(), diff --git a/dbms/src/TableFunctions/TableFunctionMySQL.cpp b/dbms/src/TableFunctions/TableFunctionMySQL.cpp index ad1aac5744e..e335af45bcb 100644 --- a/dbms/src/TableFunctions/TableFunctionMySQL.cpp +++ b/dbms/src/TableFunctions/TableFunctionMySQL.cpp @@ -87,12 +87,12 @@ DataTypePtr getDataType(const String & mysql_data_type, bool is_nullable, bool i StoragePtr TableFunctionMySQL::executeImpl(const ASTPtr & ast_function, const Context & context) const { - const auto * args_func = ast_function->as(); + const auto & args_func = ast_function->as(); - if (!args_func->arguments) + if (!args_func.arguments) throw Exception("Table function 'mysql' must have arguments.", ErrorCodes::LOGICAL_ERROR); - ASTs & args = args_func->arguments->children; + ASTs & args = args_func.arguments->children; if (args.size() < 5 || args.size() > 7) throw Exception("Table function 'mysql' requires 5-7 parameters: MySQL('host:port', database, table, 'user', 'password'[, replace_query, 'on_duplicate_clause']).", @@ -101,18 +101,18 @@ StoragePtr TableFunctionMySQL::executeImpl(const ASTPtr & ast_function, const Co for (size_t i = 0; i < args.size(); ++i) args[i] = evaluateConstantExpressionOrIdentifierAsLiteral(args[i], context); - std::string host_port = args[0]->as()->value.safeGet(); - std::string database_name = args[1]->as()->value.safeGet(); - std::string table_name = args[2]->as()->value.safeGet(); - std::string user_name = args[3]->as()->value.safeGet(); - std::string password = args[4]->as()->value.safeGet(); + std::string host_port = args[0]->as().value.safeGet(); + std::string database_name = args[1]->as().value.safeGet(); + std::string table_name = args[2]->as().value.safeGet(); + std::string user_name = args[3]->as().value.safeGet(); + std::string password = args[4]->as().value.safeGet(); bool replace_query = false; std::string on_duplicate_clause; if (args.size() >= 6) - replace_query = args[5]->as()->value.safeGet() > 0; + replace_query = args[5]->as().value.safeGet() > 0; if (args.size() == 7) - on_duplicate_clause = args[6]->as()->value.safeGet(); + on_duplicate_clause = args[6]->as().value.safeGet(); if (replace_query && !on_duplicate_clause.empty()) throw Exception( diff --git a/dbms/src/TableFunctions/TableFunctionNumbers.cpp b/dbms/src/TableFunctions/TableFunctionNumbers.cpp index 839d6eb363d..a02cd904882 100644 --- a/dbms/src/TableFunctions/TableFunctionNumbers.cpp +++ b/dbms/src/TableFunctions/TableFunctionNumbers.cpp @@ -45,7 +45,7 @@ void registerTableFunctionNumbers(TableFunctionFactory & factory) UInt64 TableFunctionNumbers::evaluateArgument(const Context & context, ASTPtr & argument) const { - return evaluateConstantExpressionOrIdentifierAsLiteral(argument, context)->as()->value.safeGet(); + return evaluateConstantExpressionOrIdentifierAsLiteral(argument, context)->as().value.safeGet(); } } diff --git a/dbms/src/TableFunctions/TableFunctionRemote.cpp b/dbms/src/TableFunctions/TableFunctionRemote.cpp index 1f552f6bef8..21611500eb7 100644 --- a/dbms/src/TableFunctions/TableFunctionRemote.cpp +++ b/dbms/src/TableFunctions/TableFunctionRemote.cpp @@ -63,7 +63,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C if (is_cluster_function) { ASTPtr ast_name = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context); - cluster_name = ast_name->as()->value.safeGet(); + cluster_name = ast_name->as().value.safeGet(); } else { @@ -83,7 +83,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C } else { - remote_database = args[arg_num]->as()->value.safeGet(); + remote_database = args[arg_num]->as().value.safeGet(); ++arg_num; @@ -103,7 +103,7 @@ StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const C else { args[arg_num] = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context); - remote_table = args[arg_num]->as()->value.safeGet(); + remote_table = args[arg_num]->as().value.safeGet(); ++arg_num; } } From 61954d855d51a61c69c5ca2e15c17fbab49c35c4 Mon Sep 17 00:00:00 2001 From: Ivan Lezhankin Date: Fri, 15 Mar 2019 20:09:14 +0300 Subject: [PATCH 10/11] More reverts --- dbms/programs/copier/ClusterCopier.cpp | 2 +- .../parseAggregateFunctionParameters.cpp | 2 +- dbms/src/Common/TypePromotion.h | 7 ++++ dbms/src/Common/typeid_cast.h | 17 +++++++--- .../DataTypes/DataTypeAggregateFunction.cpp | 2 +- dbms/src/Storages/StorageBuffer.cpp | 18 +++++----- dbms/src/Storages/StorageDictionary.cpp | 2 +- dbms/src/Storages/StorageDistributed.cpp | 14 ++++---- dbms/src/Storages/StorageFile.cpp | 2 +- dbms/src/Storages/StorageHDFS.cpp | 4 +-- dbms/src/Storages/StorageMaterializedView.cpp | 10 +++--- dbms/src/Storages/StorageMerge.cpp | 4 +-- dbms/src/Storages/StorageMergeTree.cpp | 8 ++--- dbms/src/Storages/StorageMySQL.cpp | 14 ++++---- .../Storages/StorageReplicatedMergeTree.cpp | 10 +++--- dbms/src/Storages/StorageURL.cpp | 4 +-- dbms/src/Storages/StorageXDBC.cpp | 6 ++-- .../Storages/System/StorageSystemTables.cpp | 6 ++-- .../System/StorageSystemZooKeeper.cpp | 18 +++++----- dbms/src/Storages/VirtualColumnUtils.cpp | 33 +++++++++---------- .../transformQueryForExternalDatabase.cpp | 2 +- .../TableFunctions/ITableFunctionFileLike.cpp | 6 ++-- .../src/TableFunctions/ITableFunctionXDBC.cpp | 16 ++++----- 23 files changed, 110 insertions(+), 97 deletions(-) diff --git a/dbms/programs/copier/ClusterCopier.cpp b/dbms/programs/copier/ClusterCopier.cpp index cc9f9de6485..451df591bbd 100644 --- a/dbms/programs/copier/ClusterCopier.cpp +++ b/dbms/programs/copier/ClusterCopier.cpp @@ -1179,7 +1179,7 @@ protected: /// Removes MATERIALIZED and ALIAS columns from create table query static ASTPtr removeAliasColumnsFromCreateQuery(const ASTPtr & query_ast) { - const ASTs & column_asts = query_ast->as()->columns_list->columns->children; + const ASTs & column_asts = query_ast->as().columns_list->columns->children; auto new_columns = std::make_shared(); for (const ASTPtr & column_ast : column_asts) diff --git a/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp b/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp index d724a297a7b..bcb73f1e9d9 100644 --- a/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp +++ b/dbms/src/AggregateFunctions/parseAggregateFunctionParameters.cpp @@ -15,7 +15,7 @@ namespace ErrorCodes Array getAggregateFunctionParametersArray(const ASTPtr & expression_list, const std::string & error_context) { - const ASTs & parameters = expression_list->as()->children; + const ASTs & parameters = expression_list->children; if (parameters.empty()) throw Exception("Parameters list to aggregate functions cannot be empty", ErrorCodes::BAD_ARGUMENTS); diff --git a/dbms/src/Common/TypePromotion.h b/dbms/src/Common/TypePromotion.h index b53bc25010c..e68c007e44c 100644 --- a/dbms/src/Common/TypePromotion.h +++ b/dbms/src/Common/TypePromotion.h @@ -4,6 +4,13 @@ namespace DB { +/* This base class adds public methods: + * - Derived * as() + * - const Derived * as() const + * - Derived & as() + * - const Derived & as() const + */ + template class TypePromotion { private: diff --git a/dbms/src/Common/typeid_cast.h b/dbms/src/Common/typeid_cast.h index 11b083d21d9..9285355e788 100644 --- a/dbms/src/Common/typeid_cast.h +++ b/dbms/src/Common/typeid_cast.h @@ -25,11 +25,18 @@ namespace DB template std::enable_if_t, To> typeid_cast(From & from) { - if (typeid(from) == typeid(To)) - return static_cast(from); - else - throw DB::Exception("Bad cast from type " + demangle(typeid(from).name()) + " to " + demangle(typeid(To).name()), - DB::ErrorCodes::BAD_CAST); + try + { + if (typeid(from) == typeid(To)) + return static_cast(from); + } + catch (const std::exception & e) + { + throw DB::Exception(e.what(), DB::ErrorCodes::BAD_CAST); + } + + throw DB::Exception("Bad cast from type " + demangle(typeid(from).name()) + " to " + demangle(typeid(To).name()), + DB::ErrorCodes::BAD_CAST); } template diff --git a/dbms/src/DataTypes/DataTypeAggregateFunction.cpp b/dbms/src/DataTypes/DataTypeAggregateFunction.cpp index c604d58cbaa..a5dd5f8be62 100644 --- a/dbms/src/DataTypes/DataTypeAggregateFunction.cpp +++ b/dbms/src/DataTypes/DataTypeAggregateFunction.cpp @@ -346,7 +346,7 @@ static DataTypePtr create(const ASTPtr & arguments) throw Exception("Unexpected level of parameters to aggregate function", ErrorCodes::SYNTAX_ERROR); function_name = parametric->name; - const ASTs & parameters = parametric->arguments->as()->children; + const ASTs & parameters = parametric->arguments->children; params_row.resize(parameters.size()); for (size_t i = 0; i < parameters.size(); ++i) diff --git a/dbms/src/Storages/StorageBuffer.cpp b/dbms/src/Storages/StorageBuffer.cpp index 0fdb8d056d4..c9a1e2fe52b 100644 --- a/dbms/src/Storages/StorageBuffer.cpp +++ b/dbms/src/Storages/StorageBuffer.cpp @@ -713,17 +713,17 @@ void registerStorageBuffer(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); - String destination_database = engine_args[0]->as()->value.safeGet(); - String destination_table = engine_args[1]->as()->value.safeGet(); + String destination_database = engine_args[0]->as().value.safeGet(); + String destination_table = engine_args[1]->as().value.safeGet(); - UInt64 num_buckets = applyVisitor(FieldVisitorConvertToNumber(), engine_args[2]->as()->value); + UInt64 num_buckets = applyVisitor(FieldVisitorConvertToNumber(), engine_args[2]->as().value); - Int64 min_time = applyVisitor(FieldVisitorConvertToNumber(), engine_args[3]->as()->value); - Int64 max_time = applyVisitor(FieldVisitorConvertToNumber(), engine_args[4]->as()->value); - UInt64 min_rows = applyVisitor(FieldVisitorConvertToNumber(), engine_args[5]->as()->value); - UInt64 max_rows = applyVisitor(FieldVisitorConvertToNumber(), engine_args[6]->as()->value); - UInt64 min_bytes = applyVisitor(FieldVisitorConvertToNumber(), engine_args[7]->as()->value); - UInt64 max_bytes = applyVisitor(FieldVisitorConvertToNumber(), engine_args[8]->as()->value); + Int64 min_time = applyVisitor(FieldVisitorConvertToNumber(), engine_args[3]->as().value); + Int64 max_time = applyVisitor(FieldVisitorConvertToNumber(), engine_args[4]->as().value); + UInt64 min_rows = applyVisitor(FieldVisitorConvertToNumber(), engine_args[5]->as().value); + UInt64 max_rows = applyVisitor(FieldVisitorConvertToNumber(), engine_args[6]->as().value); + UInt64 min_bytes = applyVisitor(FieldVisitorConvertToNumber(), engine_args[7]->as().value); + UInt64 max_bytes = applyVisitor(FieldVisitorConvertToNumber(), engine_args[8]->as().value); return StorageBuffer::create( args.table_name, args.columns, diff --git a/dbms/src/Storages/StorageDictionary.cpp b/dbms/src/Storages/StorageDictionary.cpp index 3ad562543fd..2c8c76005d4 100644 --- a/dbms/src/Storages/StorageDictionary.cpp +++ b/dbms/src/Storages/StorageDictionary.cpp @@ -101,7 +101,7 @@ void registerStorageDictionary(StorageFactory & factory) ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); args.engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(args.engine_args[0], args.local_context); - String dictionary_name = args.engine_args[0]->as()->value.safeGet(); + String dictionary_name = args.engine_args[0]->as().value.safeGet(); return StorageDictionary::create( args.table_name, args.columns, args.context, args.attach, dictionary_name); diff --git a/dbms/src/Storages/StorageDistributed.cpp b/dbms/src/Storages/StorageDistributed.cpp index 5ea027ba1f7..27963a914b2 100644 --- a/dbms/src/Storages/StorageDistributed.cpp +++ b/dbms/src/Storages/StorageDistributed.cpp @@ -75,9 +75,9 @@ ASTPtr rewriteSelectQuery(const ASTPtr & query, const std::string & database, co { auto modified_query_ast = query->clone(); if (table_function_ptr) - modified_query_ast->as()->addTableFunction(table_function_ptr); + modified_query_ast->as().addTableFunction(table_function_ptr); else - modified_query_ast->as()->replaceDatabaseAndTable(database, table); + modified_query_ast->as().replaceDatabaseAndTable(database, table); return modified_query_ast; } @@ -468,14 +468,14 @@ void StorageDistributed::ClusterNodeData::shutdownAndDropAllData() /// using constraints from "WHERE" condition, otherwise returns `nullptr` ClusterPtr StorageDistributed::skipUnusedShards(ClusterPtr cluster, const SelectQueryInfo & query_info) { - const auto * select = query_info.query->as(); + const auto & select = query_info.query->as(); - if (!select->where_expression) + if (!select.where_expression) { return nullptr; } - const auto & blocks = evaluateExpressionOverConstantCondition(select->where_expression, sharding_key_expr); + const auto & blocks = evaluateExpressionOverConstantCondition(select.where_expression, sharding_key_expr); // Can't get definite answer if we can skip any shards if (!blocks) @@ -528,8 +528,8 @@ void registerStorageDistributed(StorageFactory & factory) engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); engine_args[2] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[2], args.local_context); - String remote_database = engine_args[1]->as()->value.safeGet(); - String remote_table = engine_args[2]->as()->value.safeGet(); + String remote_database = engine_args[1]->as().value.safeGet(); + String remote_table = engine_args[2]->as().value.safeGet(); const auto & sharding_key = engine_args.size() == 4 ? engine_args[3] : nullptr; diff --git a/dbms/src/Storages/StorageFile.cpp b/dbms/src/Storages/StorageFile.cpp index 04b4c3853f8..c6eb867f32a 100644 --- a/dbms/src/Storages/StorageFile.cpp +++ b/dbms/src/Storages/StorageFile.cpp @@ -291,7 +291,7 @@ void registerStorageFile(StorageFactory & factory) ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); - String format_name = engine_args[0]->as()->value.safeGet(); + String format_name = engine_args[0]->as().value.safeGet(); int source_fd = -1; String source_path; diff --git a/dbms/src/Storages/StorageHDFS.cpp b/dbms/src/Storages/StorageHDFS.cpp index 4222fcf4dd8..aec846f1a58 100644 --- a/dbms/src/Storages/StorageHDFS.cpp +++ b/dbms/src/Storages/StorageHDFS.cpp @@ -163,11 +163,11 @@ void registerStorageHDFS(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); - String url = engine_args[0]->as()->value.safeGet(); + String url = engine_args[0]->as().value.safeGet(); engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); - String format_name = engine_args[1]->as()->value.safeGet(); + String format_name = engine_args[1]->as().value.safeGet(); return StorageHDFS::create(url, args.table_name, format_name, args.columns, args.context); }); diff --git a/dbms/src/Storages/StorageMaterializedView.cpp b/dbms/src/Storages/StorageMaterializedView.cpp index 5ef142f6857..fd63053c78a 100644 --- a/dbms/src/Storages/StorageMaterializedView.cpp +++ b/dbms/src/Storages/StorageMaterializedView.cpp @@ -55,7 +55,7 @@ static void extractDependentTable(ASTSelectQuery & query, String & select_databa auto & inner_query = ast_select->list_of_selects->children.at(0); - extractDependentTable(*inner_query->as(), select_database_name, select_table_name); + extractDependentTable(inner_query->as(), select_database_name, select_table_name); } else throw Exception("Logical error while creating StorageMaterializedView." @@ -80,7 +80,7 @@ static void checkAllowedQueries(const ASTSelectQuery & query) const auto & inner_query = ast_select->list_of_selects->children.at(0); - checkAllowedQueries(*inner_query->as()); + checkAllowedQueries(inner_query->as()); } } @@ -110,9 +110,9 @@ StorageMaterializedView::StorageMaterializedView( inner_query = query.select->list_of_selects->children.at(0); - auto * select_query = inner_query->as(); - extractDependentTable(*select_query, select_database_name, select_table_name); - checkAllowedQueries(*select_query); + auto & select_query = inner_query->as(); + extractDependentTable(select_query, select_database_name, select_table_name); + checkAllowedQueries(select_query); if (!select_table_name.empty()) global_context.addDependency( diff --git a/dbms/src/Storages/StorageMerge.cpp b/dbms/src/Storages/StorageMerge.cpp index 0622020bc58..225ae9c2a07 100644 --- a/dbms/src/Storages/StorageMerge.cpp +++ b/dbms/src/Storages/StorageMerge.cpp @@ -491,8 +491,8 @@ void registerStorageMerge(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); engine_args[1] = evaluateConstantExpressionAsLiteral(engine_args[1], args.local_context); - String source_database = engine_args[0]->as()->value.safeGet(); - String table_name_regexp = engine_args[1]->as()->value.safeGet(); + String source_database = engine_args[0]->as().value.safeGet(); + String table_name_regexp = engine_args[1]->as().value.safeGet(); return StorageMerge::create( args.table_name, args.columns, diff --git a/dbms/src/Storages/StorageMergeTree.cpp b/dbms/src/Storages/StorageMergeTree.cpp index 44264b691b7..fd356e75e8f 100644 --- a/dbms/src/Storages/StorageMergeTree.cpp +++ b/dbms/src/Storages/StorageMergeTree.cpp @@ -235,13 +235,13 @@ void StorageMergeTree::alter( IDatabase::ASTModifier storage_modifier = [&] (IAST & ast) { - auto * storage_ast = ast.as(); + auto & storage_ast = ast.as(); if (new_order_by_ast.get() != data.order_by_ast.get()) - storage_ast->set(storage_ast->order_by, new_order_by_ast); + storage_ast.set(storage_ast.order_by, new_order_by_ast); if (new_primary_key_ast.get() != data.primary_key_ast.get()) - storage_ast->set(storage_ast->primary_key, new_primary_key_ast); + storage_ast.set(storage_ast.primary_key, new_primary_key_ast); }; context.getDatabase(current_database_name)->alterTable(context, current_table_name, new_columns, new_indices, storage_modifier); @@ -941,7 +941,7 @@ void StorageMergeTree::attachPartition(const ASTPtr & partition, bool attach_par String partition_id; if (attach_part) - partition_id = partition->as()->value.safeGet(); + partition_id = partition->as().value.safeGet(); else partition_id = data.getPartitionIDFromQuery(partition, context); diff --git a/dbms/src/Storages/StorageMySQL.cpp b/dbms/src/Storages/StorageMySQL.cpp index 2d06d032935..cd700529b79 100644 --- a/dbms/src/Storages/StorageMySQL.cpp +++ b/dbms/src/Storages/StorageMySQL.cpp @@ -199,21 +199,21 @@ void registerStorageMySQL(StorageFactory & factory) engine_args[i] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[i], args.local_context); /// 3306 is the default MySQL port. - auto parsed_host_port = parseAddress(engine_args[0]->as()->value.safeGet(), 3306); + auto parsed_host_port = parseAddress(engine_args[0]->as().value.safeGet(), 3306); - const String & remote_database = engine_args[1]->as()->value.safeGet(); - const String & remote_table = engine_args[2]->as()->value.safeGet(); - const String & username = engine_args[3]->as()->value.safeGet(); - const String & password = engine_args[4]->as()->value.safeGet(); + const String & remote_database = engine_args[1]->as().value.safeGet(); + const String & remote_table = engine_args[2]->as().value.safeGet(); + const String & username = engine_args[3]->as().value.safeGet(); + const String & password = engine_args[4]->as().value.safeGet(); mysqlxx::Pool pool(remote_database, parsed_host_port.first, username, password, parsed_host_port.second); bool replace_query = false; std::string on_duplicate_clause; if (engine_args.size() >= 6) - replace_query = engine_args[5]->as()->value.safeGet(); + replace_query = engine_args[5]->as().value.safeGet(); if (engine_args.size() == 7) - on_duplicate_clause = engine_args[6]->as()->value.safeGet(); + on_duplicate_clause = engine_args[6]->as().value.safeGet(); if (replace_query && !on_duplicate_clause.empty()) throw Exception( diff --git a/dbms/src/Storages/StorageReplicatedMergeTree.cpp b/dbms/src/Storages/StorageReplicatedMergeTree.cpp index d4168cb07b7..6c51e5d0f55 100644 --- a/dbms/src/Storages/StorageReplicatedMergeTree.cpp +++ b/dbms/src/Storages/StorageReplicatedMergeTree.cpp @@ -447,17 +447,17 @@ void StorageReplicatedMergeTree::setTableStructure(ColumnsDescription new_column storage_modifier = [&](IAST & ast) { - auto * storage_ast = ast.as(); + auto & storage_ast = ast.as(); - if (!storage_ast->order_by) + if (!storage_ast.order_by) throw Exception( "ALTER MODIFY ORDER BY of default-partitioned tables is not supported", ErrorCodes::LOGICAL_ERROR); if (new_primary_key_ast.get() != data.primary_key_ast.get()) - storage_ast->set(storage_ast->primary_key, new_primary_key_ast); + storage_ast.set(storage_ast.primary_key, new_primary_key_ast); - storage_ast->set(storage_ast->order_by, new_order_by_ast); + storage_ast.set(storage_ast.order_by, new_order_by_ast); }; } @@ -3567,7 +3567,7 @@ void StorageReplicatedMergeTree::attachPartition(const ASTPtr & partition, bool String partition_id; if (attach_part) - partition_id = partition->as()->value.safeGet(); + partition_id = partition->as().value.safeGet(); else partition_id = data.getPartitionIDFromQuery(partition, query_context); diff --git a/dbms/src/Storages/StorageURL.cpp b/dbms/src/Storages/StorageURL.cpp index 3a4313099b2..71575f27b1b 100644 --- a/dbms/src/Storages/StorageURL.cpp +++ b/dbms/src/Storages/StorageURL.cpp @@ -202,12 +202,12 @@ void registerStorageURL(StorageFactory & factory) engine_args[0] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[0], args.local_context); - String url = engine_args[0]->as()->value.safeGet(); + String url = engine_args[0]->as().value.safeGet(); Poco::URI uri(url); engine_args[1] = evaluateConstantExpressionOrIdentifierAsLiteral(engine_args[1], args.local_context); - String format_name = engine_args[1]->as()->value.safeGet(); + String format_name = engine_args[1]->as().value.safeGet(); return StorageURL::create(uri, args.table_name, format_name, args.columns, args.context); }); diff --git a/dbms/src/Storages/StorageXDBC.cpp b/dbms/src/Storages/StorageXDBC.cpp index e2f7e7975df..3b02b86ad7f 100644 --- a/dbms/src/Storages/StorageXDBC.cpp +++ b/dbms/src/Storages/StorageXDBC.cpp @@ -115,10 +115,10 @@ namespace BridgeHelperPtr bridge_helper = std::make_shared>(args.context, args.context.getSettingsRef().http_receive_timeout.value, - engine_args[0]->as()->value.safeGet()); + engine_args[0]->as().value.safeGet()); return std::make_shared(args.table_name, - engine_args[1]->as()->value.safeGet(), - engine_args[2]->as()->value.safeGet(), + engine_args[1]->as().value.safeGet(), + engine_args[2]->as().value.safeGet(), args.columns, args.context, bridge_helper); diff --git a/dbms/src/Storages/System/StorageSystemTables.cpp b/dbms/src/Storages/System/StorageSystemTables.cpp index 85fa9c2a0fa..3413e8609f4 100644 --- a/dbms/src/Storages/System/StorageSystemTables.cpp +++ b/dbms/src/Storages/System/StorageSystemTables.cpp @@ -240,10 +240,10 @@ protected: if (ast) { - const auto * ast_create = ast->as(); - if (ast_create->storage) + const auto & ast_create = ast->as(); + if (ast_create.storage) { - engine_full = queryToString(*ast_create->storage); + engine_full = queryToString(*ast_create.storage); static const char * const extra_head = " ENGINE = "; if (startsWith(engine_full, extra_head)) diff --git a/dbms/src/Storages/System/StorageSystemZooKeeper.cpp b/dbms/src/Storages/System/StorageSystemZooKeeper.cpp index 7533e88aa21..a23d0a79957 100644 --- a/dbms/src/Storages/System/StorageSystemZooKeeper.cpp +++ b/dbms/src/Storages/System/StorageSystemZooKeeper.cpp @@ -59,17 +59,17 @@ static bool extractPathImpl(const IAST & elem, String & res) if (function->name == "equals") { - const auto * args = function->arguments->as(); + const auto & args = function->arguments->as(); const IAST * value; - if (args->children.size() != 2) + if (args.children.size() != 2) return false; const ASTIdentifier * ident; - 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); + if ((ident = args.children.at(0)->as())) + value = args.children.at(1).get(); + else if ((ident = args.children.at(1)->as())) + value = args.children.at(0).get(); else return false; @@ -95,12 +95,12 @@ static bool extractPathImpl(const IAST & elem, String & res) */ static String extractPath(const ASTPtr & query) { - const auto * select = query->as(); - if (!select->where_expression) + const auto & select = query->as(); + if (!select.where_expression) return ""; String res; - return extractPathImpl(*select->where_expression, res) ? res : ""; + return extractPathImpl(*select.where_expression, res) ? res : ""; } diff --git a/dbms/src/Storages/VirtualColumnUtils.cpp b/dbms/src/Storages/VirtualColumnUtils.cpp index 43ca07e5a98..9f634cc0eec 100644 --- a/dbms/src/Storages/VirtualColumnUtils.cpp +++ b/dbms/src/Storages/VirtualColumnUtils.cpp @@ -76,18 +76,17 @@ String chooseSuffixForSet(const NamesAndTypesList & columns, const std::vectoras(); - if (!select->with_expression_list) + auto & select = ast->as(); + if (!select.with_expression_list) { - select->with_expression_list = std::make_shared(); - select->children.insert(select->children.begin(), select->with_expression_list); + select.with_expression_list = std::make_shared(); + select.children.insert(select.children.begin(), select.with_expression_list); } - auto * with = select->with_expression_list->as(); auto literal = std::make_shared(value); literal->alias = column_name; literal->prefer_alias_to_column_name = true; - with->children.push_back(literal); + select.with_expression_list->children.push_back(literal); } /// Verifying that the function depends only on the specified columns @@ -126,18 +125,18 @@ static ASTPtr buildWhereExpression(const ASTs & functions) if (functions.size() == 1) return functions[0]; ASTPtr new_query = std::make_shared(); - auto * new_function = new_query->as(); - new_function->name = "and"; - new_function->arguments = std::make_shared(); - new_function->arguments->children = functions; - new_function->children.push_back(new_function->arguments); + auto & new_function = new_query->as(); + new_function.name = "and"; + new_function.arguments = std::make_shared(); + new_function.arguments->children = functions; + new_function.children.push_back(new_function.arguments); return new_query; } void filterBlockWithQuery(const ASTPtr & query, Block & block, const Context & context) { - const auto * select = query->as(); - if (!select->where_expression && !select->prewhere_expression) + const auto & select = query->as(); + if (!select.where_expression && !select.prewhere_expression) return; NameSet columns; @@ -146,10 +145,10 @@ void filterBlockWithQuery(const ASTPtr & query, Block & block, const Context & c /// We will create an expression that evaluates the expressions in WHERE and PREWHERE, depending only on the existing columns. std::vector functions; - if (select->where_expression) - extractFunctions(select->where_expression, columns, functions); - if (select->prewhere_expression) - extractFunctions(select->prewhere_expression, columns, functions); + if (select.where_expression) + extractFunctions(select.where_expression, columns, functions); + if (select.prewhere_expression) + extractFunctions(select.prewhere_expression, columns, functions); ASTPtr expression_ast = buildWhereExpression(functions); if (!expression_ast) diff --git a/dbms/src/Storages/transformQueryForExternalDatabase.cpp b/dbms/src/Storages/transformQueryForExternalDatabase.cpp index 4e257cf63ae..d54996515d3 100644 --- a/dbms/src/Storages/transformQueryForExternalDatabase.cpp +++ b/dbms/src/Storages/transformQueryForExternalDatabase.cpp @@ -112,7 +112,7 @@ String transformQueryForExternalDatabase( * copy only compatible parts of it. */ - auto & original_where = clone_query->as()->where_expression; + auto & original_where = clone_query->as().where_expression; if (original_where) { replaceConstFunction(*original_where, context, available_columns); diff --git a/dbms/src/TableFunctions/ITableFunctionFileLike.cpp b/dbms/src/TableFunctions/ITableFunctionFileLike.cpp index 0ef6139fdbc..fe8af831b56 100644 --- a/dbms/src/TableFunctions/ITableFunctionFileLike.cpp +++ b/dbms/src/TableFunctions/ITableFunctionFileLike.cpp @@ -36,9 +36,9 @@ StoragePtr ITableFunctionFileLike::executeImpl(const ASTPtr & ast_function, cons for (size_t i = 0; i < 3; ++i) args[i] = evaluateConstantExpressionOrIdentifierAsLiteral(args[i], context); - std::string filename = args[0]->as()->value.safeGet(); - std::string format = args[1]->as()->value.safeGet(); - std::string structure = args[2]->as()->value.safeGet(); + std::string filename = args[0]->as().value.safeGet(); + std::string format = args[1]->as().value.safeGet(); + std::string structure = args[2]->as().value.safeGet(); // Create sample block std::vector structure_vals; diff --git a/dbms/src/TableFunctions/ITableFunctionXDBC.cpp b/dbms/src/TableFunctions/ITableFunctionXDBC.cpp index 9476946dc85..32011dc8f8a 100644 --- a/dbms/src/TableFunctions/ITableFunctionXDBC.cpp +++ b/dbms/src/TableFunctions/ITableFunctionXDBC.cpp @@ -29,12 +29,12 @@ namespace ErrorCodes StoragePtr ITableFunctionXDBC::executeImpl(const ASTPtr & ast_function, const Context & context) const { - const auto * args_func = ast_function->as(); + const auto & args_func = ast_function->as(); - if (!args_func->arguments) + if (!args_func.arguments) throw Exception("Table function '" + getName() + "' must have arguments.", ErrorCodes::LOGICAL_ERROR); - ASTs & args = args_func->arguments->children; + ASTs & args = args_func.arguments->children; if (args.size() != 2 && args.size() != 3) throw Exception("Table function '" + getName() + "' requires 2 or 3 arguments: " + getName() + "('DSN', table) or " + getName() + "('DSN', schema, table)", @@ -49,14 +49,14 @@ StoragePtr ITableFunctionXDBC::executeImpl(const ASTPtr & ast_function, const Co if (args.size() == 3) { - connection_string = args[0]->as()->value.safeGet(); - schema_name = args[1]->as()->value.safeGet(); - table_name = args[2]->as()->value.safeGet(); + connection_string = args[0]->as().value.safeGet(); + schema_name = args[1]->as().value.safeGet(); + table_name = args[2]->as().value.safeGet(); } else if (args.size() == 2) { - connection_string = args[0]->as()->value.safeGet(); - table_name = args[1]->as()->value.safeGet(); + connection_string = args[0]->as().value.safeGet(); + table_name = args[1]->as().value.safeGet(); } /* Infer external table structure */ From b67e79430d5300c442a2a14c8c823006ed6d83c9 Mon Sep 17 00:00:00 2001 From: Ivan Lezhankin Date: Fri, 15 Mar 2019 20:22:19 +0300 Subject: [PATCH 11/11] Fix style --- dbms/src/Common/TypePromotion.h | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/dbms/src/Common/TypePromotion.h b/dbms/src/Common/TypePromotion.h index e68c007e44c..18ac0821b2c 100644 --- a/dbms/src/Common/TypePromotion.h +++ b/dbms/src/Common/TypePromotion.h @@ -2,7 +2,8 @@ #include -namespace DB { +namespace DB +{ /* This base class adds public methods: * - Derived * as() @@ -12,7 +13,8 @@ namespace DB { */ template -class TypePromotion { +class TypePromotion +{ private: /// Need a helper-struct to fight the lack of the function-template partial specialization. template >