| 1 | #include <Parsers/ASTWithAlias.h> |
| 2 | #include <IO/WriteBufferFromOStream.h> |
| 3 | #include <IO/WriteHelpers.h> |
| 4 | |
| 5 | |
| 6 | namespace DB |
| 7 | { |
| 8 | |
| 9 | void ASTWithAlias::writeAlias(const String & name, const FormatSettings & settings) const |
| 10 | { |
| 11 | settings.ostr << (settings.hilite ? hilite_keyword : "" ) << " AS " << (settings.hilite ? hilite_alias : "" ); |
| 12 | settings.writeIdentifier(name); |
| 13 | settings.ostr << (settings.hilite ? hilite_none : "" ); |
| 14 | } |
| 15 | |
| 16 | |
| 17 | void ASTWithAlias::formatImpl(const FormatSettings & settings, FormatState & state, FormatStateStacked frame) const |
| 18 | { |
| 19 | /// If we have previously output this node elsewhere in the query, now it is enough to output only the alias. |
| 20 | /// This is needed because the query can become extraordinary large after substitution of aliases. |
| 21 | if (!alias.empty() && !state.printed_asts_with_alias.emplace(frame.current_select, alias, getTreeHash()).second) |
| 22 | { |
| 23 | settings.writeIdentifier(alias); |
| 24 | } |
| 25 | else |
| 26 | { |
| 27 | /// If there is an alias, then parentheses are required around the entire expression, including the alias. |
| 28 | /// Because a record of the form `0 AS x + 0` is syntactically invalid. |
| 29 | if (frame.need_parens && !alias.empty()) |
| 30 | settings.ostr << '('; |
| 31 | |
| 32 | formatImplWithoutAlias(settings, state, frame); |
| 33 | |
| 34 | if (!alias.empty()) |
| 35 | { |
| 36 | writeAlias(alias, settings); |
| 37 | if (frame.need_parens) |
| 38 | settings.ostr << ')'; |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | void ASTWithAlias::appendColumnName(WriteBuffer & ostr) const |
| 44 | { |
| 45 | if (prefer_alias_to_column_name && !alias.empty()) |
| 46 | writeString(alias, ostr); |
| 47 | else |
| 48 | appendColumnNameImpl(ostr); |
| 49 | } |
| 50 | |
| 51 | } |
| 52 | |