Fix transform query for external databases in presense of aliases #12032

This commit is contained in:
Alexey Milovidov 2020-07-06 04:50:45 +03:00
parent ea0fb005fb
commit 95a7a09c37
4 changed files with 42 additions and 2 deletions

View File

@ -257,7 +257,7 @@ struct ColumnAliasesMatcher
if (!last_table)
{
IdentifierSemantic::coverName(node, alias);
node.setAlias("");
node.setAlias({});
}
}
else if (node.compound())

View File

@ -76,7 +76,7 @@ static void cleanAliasAndCollectIdentifiers(ASTPtr & predicate, std::vector<ASTI
}
if (const auto alias = predicate->tryGetAlias(); !alias.empty())
predicate->setAlias("");
predicate->setAlias({});
if (ASTIdentifier * identifier = predicate->as<ASTIdentifier>())
identifiers.emplace_back(identifier);

View File

@ -5,6 +5,7 @@
#include <Parsers/parseQuery.h>
#include <DataTypes/DataTypesNumber.h>
#include <DataTypes/DataTypeDateTime.h>
#include <DataTypes/DataTypeString.h>
#include <Interpreters/Context.h>
#include <Databases/DatabaseMemory.h>
#include <Storages/StorageMemory.h>
@ -27,6 +28,8 @@ struct State
{"apply_type", std::make_shared<DataTypeUInt8>()},
{"apply_status", std::make_shared<DataTypeUInt8>()},
{"create_time", std::make_shared<DataTypeDateTime>()},
{"field", std::make_shared<DataTypeString>()},
{"value", std::make_shared<DataTypeString>()},
};
static const State & instance()
@ -117,3 +120,12 @@ TEST(TransformQueryForExternalDatabase, Issue7245)
R"(SELECT "apply_id", "apply_type", "apply_status", "create_time" FROM "test"."table" WHERE ("apply_type" = 2) AND ("create_time" > '2018-12-25 01:02:03') AND ("apply_status" IN (3, 4)))",
state.context, state.columns);
}
TEST(TransformQueryForExternalDatabase, Aliases)
{
const State & state = State::instance();
check("SELECT field AS value, field AS display WHERE field NOT IN ('') AND display LIKE '%test%'",
R"(SELECT "field" FROM "test"."table" WHERE ("field" NOT IN ('')) AND ("field" LIKE '%test%'))",
state.context, state.columns);
}

View File

@ -71,6 +71,24 @@ public:
}
};
class DropAliasesMatcher
{
public:
struct Data {};
Data data;
static bool needChildVisit(ASTPtr &, const ASTPtr &)
{
return true;
}
static void visit(ASTPtr & node, Data)
{
if (!node->tryGetAlias().empty())
node->setAlias({});
}
};
void replaceConstantExpressions(ASTPtr & node, const Context & context, const NamesAndTypesList & all_columns)
{
auto syntax_result = SyntaxAnalyzer(context).analyze(node, all_columns);
@ -80,6 +98,13 @@ void replaceConstantExpressions(ASTPtr & node, const Context & context, const Na
visitor.visit(node);
}
void dropAliases(ASTPtr & node)
{
DropAliasesMatcher::Data data;
InDepthNodeVisitor<DropAliasesMatcher, true> visitor(data);
visitor.visit(node);
}
bool isCompatible(const IAST & node)
{
@ -192,6 +217,9 @@ String transformQueryForExternalDatabase(
}
}
ASTPtr select_ptr = select;
dropAliases(select_ptr);
std::stringstream out;
IAST::FormatSettings settings(out, true);
settings.identifier_quoting_style = identifier_quoting_style;