Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 163 additions & 9 deletions clickhouse/types/type_parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#include <mutex>
#include <array>
#include <unordered_map>
#include <unordered_set>

#if defined _win_
#include <string.h>
Expand Down Expand Up @@ -84,6 +85,112 @@ static const std::unordered_map<std::string, Type::Code> kTypeCode = {
{ "JSON", Type::JSON },
};

// Type names that the server reads in any letter case: the families with
// system.data_type_families.case_insensitive = 1, and Array, Map, Enum8 and Enum16. Keys are lower case.
static const std::unordered_map<std::string, std::string> kCaseInsensitiveTypeName = {
{ "bool", "Bool" },
{ "datetime", "DateTime" },
{ "datetime64", "DateTime64" },
{ "date", "Date" },
{ "date32", "Date32" },
{ "decimal", "Decimal" },
{ "decimal32", "Decimal32" },
{ "decimal64", "Decimal64" },
{ "decimal128", "Decimal128" },
{ "json", "JSON" },
{ "time", "Time" },
{ "time64", "Time64" },
{ "array", "Array" },
{ "map", "Map" },
{ "enum8", "Enum8" },
{ "enum16", "Enum16" },
};

// Type aliases of the server (system.data_type_families.alias_to), also in any letter case.
// Keys are upper case, words are separated by one space.
static const std::unordered_map<std::string, std::string> kTypeAlias = {
{ "BOOLEAN", "Bool" },
{ "TIMESTAMP", "DateTime" },
{ "DEC", "Decimal" },
{ "FIXED", "Decimal" },
{ "NUMERIC", "Decimal" },
{ "BINARY", "FixedString" },
{ "FLOAT", "Float32" },
{ "REAL", "Float32" },
{ "SINGLE", "Float32" },
{ "DOUBLE", "Float64" },
{ "DOUBLE PRECISION", "Float64" },
{ "INET4", "IPv4" },
{ "INET6", "IPv6" },
{ "BYTE", "Int8" },
{ "INT1", "Int8" },
{ "INT1 SIGNED", "Int8" },
{ "TINYINT", "Int8" },
{ "TINYINT SIGNED", "Int8" },
{ "SMALLINT", "Int16" },
{ "SMALLINT SIGNED", "Int16" },
{ "INT", "Int32" },
{ "INT SIGNED", "Int32" },
{ "INTEGER", "Int32" },
{ "INTEGER SIGNED", "Int32" },
{ "MEDIUMINT", "Int32" },
{ "MEDIUMINT SIGNED", "Int32" },
{ "BIGINT", "Int64" },
{ "BIGINT SIGNED", "Int64" },
{ "SIGNED", "Int64" },
{ "INT1 UNSIGNED", "UInt8" },
{ "TINYINT UNSIGNED", "UInt8" },
{ "SMALLINT UNSIGNED", "UInt16" },
{ "YEAR", "UInt16" },
{ "INT UNSIGNED", "UInt32" },
{ "INTEGER UNSIGNED", "UInt32" },
{ "MEDIUMINT UNSIGNED", "UInt32" },
{ "BIGINT UNSIGNED", "UInt64" },
{ "BIT", "UInt64" },
{ "SET", "UInt64" },
{ "UNSIGNED", "UInt64" },
{ "BINARY LARGE OBJECT", "String" },
{ "BINARY VARYING", "String" },
{ "BLOB", "String" },
{ "BYTEA", "String" },
{ "CHAR", "String" },
{ "CHAR LARGE OBJECT", "String" },
{ "CHAR VARYING", "String" },
{ "CHARACTER", "String" },
{ "CHARACTER LARGE OBJECT", "String" },
{ "CHARACTER VARYING", "String" },
{ "CLOB", "String" },
{ "LONGBLOB", "String" },
{ "LONGTEXT", "String" },
{ "MEDIUMBLOB", "String" },
{ "MEDIUMTEXT", "String" },
{ "NATIONAL CHAR", "String" },
{ "NATIONAL CHAR VARYING", "String" },
{ "NATIONAL CHARACTER", "String" },
{ "NATIONAL CHARACTER LARGE OBJECT", "String" },
{ "NATIONAL CHARACTER VARYING", "String" },
{ "NCHAR", "String" },
{ "NCHAR LARGE OBJECT", "String" },
{ "NCHAR VARYING", "String" },
{ "NVARCHAR", "String" },
{ "TEXT", "String" },
{ "TINYBLOB", "String" },
{ "TINYTEXT", "String" },
{ "VARBINARY", "String" },
{ "VARCHAR", "String" },
{ "VARCHAR2", "String" },
};

// Every proper prefix (in words) of a multi-word alias, upper case: "NATIONAL", "NATIONAL CHARACTER", ...
static const std::unordered_set<std::string> kMultiWordAliasPrefix = [] {
std::unordered_set<std::string> prefixes;
for (const auto& [alias, canonical] : kTypeAlias) {
for (size_t pos = alias.find(' '); pos != std::string::npos; pos = alias.find(' ', pos + 1))
prefixes.insert(alias.substr(0, pos));
}
return prefixes;
}();

static constexpr auto kUnescapeMap = [](){
std::array<char, 256> m{};
// std::fill or m.fill are not yet constant expressions in C++17
Expand Down Expand Up @@ -111,16 +218,57 @@ inline int CompateStringsCaseInsensitive(const L& left, const R& right) {
#endif
}

static std::string ToAsciiLower(const StringView& str) {
std::string out(str.data(), str.size());
for (auto& c : out) {
if (c >= 'A' && c <= 'Z') c = static_cast<char>(c - 'A' + 'a');
}
return out;
}

static std::string ToAsciiUpper(const StringView& str) {
std::string out(str.data(), str.size());
for (auto& c : out) {
if (c >= 'a' && c <= 'z') c = static_cast<char>(c - 'a' + 'A');
}
return out;
}

// Name of the type that the server makes from `name`: the canonical name, an alias or the same name in
// another letter case. Returns `name` itself when it is not a known type name.
static std::string GetCanonicalTypeName(const std::string& name) {
if (kTypeCode.count(name))
return name;

const auto alias = kTypeAlias.find(ToAsciiUpper(name));
if (alias != kTypeAlias.end())
return alias->second;

const auto lower = kCaseInsensitiveTypeName.find(ToAsciiLower(name));
if (lower != kCaseInsensitiveTypeName.end())
return lower->second;

return name;
}

// True if `first` and `second` are the first words of a multi-word alias, e.g. "INT" and "UNSIGNED".
static bool IsMultiWordAliasPart(const std::string& first, const StringView& second) {
return kMultiWordAliasPrefix.count(ToAsciiUpper(first) + " " + ToAsciiUpper(second)) != 0
|| kTypeAlias.count(ToAsciiUpper(first) + " " + ToAsciiUpper(second)) != 0;
}

static Type::Code GetTypeCode(const std::string& name) {
auto it = kTypeCode.find(name);
auto it = kTypeCode.find(GetCanonicalTypeName(name));
if (it != kTypeCode.end()) {
return it->second;
}

return Type::Void;
}

static TypeAst::Meta GetTypeMeta(const StringView& name) {
static TypeAst::Meta GetTypeMeta(const std::string& type_name) {
const std::string name = GetCanonicalTypeName(type_name);

if (name == "Array") {
return TypeAst::Array;
}
Expand Down Expand Up @@ -197,14 +345,20 @@ bool TypeParser::Parse(TypeAst* type) {
}
case Token::QuotedIdentifier:
case Token::Name:
if (!type_->name.empty()) {
// A second Name token on the same element means the
// previous one was a field name in a named-tuple element
// (e.g. "a" in "Tuple(a Int32, …)").
type_->element_name = std::move(type_->name);
if (!type_->name.empty() && token.type == Token::Name && IsMultiWordAliasPart(type_->name, token.value)) {
// A word of an alias with several words, e.g. "UNSIGNED" in "INT UNSIGNED".
type_->name += ' ';
type_->name += token.value.to_string();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quoted tuple fields join aliases

Medium Severity

Alias joining appends the next bare word to any name already stored, including a quoted identifier. A quoted tuple field that begins a multi-word alias is absorbed into the type: the field name is dropped, and a shorter integer alias can be chosen instead of standalone SIGNED or UNSIGNED.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 193a9ed. Configure here.

} else {
if (!type_->name.empty()) {
// A second Name token on the same element means the
// previous one was a field name in a named-tuple element
// (e.g. "a" in "Tuple(a Int32, …)").
type_->element_name = std::move(type_->name);
}
type_->name = token.value.to_string();
}
type_->meta = GetTypeMeta(token.value);
type_->name = token.value.to_string();
type_->meta = GetTypeMeta(type_->name);
type_->code = GetTypeCode(type_->name);
break;
case Token::Number: {
Expand Down
108 changes: 108 additions & 0 deletions ut/CreateColumnByType_ut.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,114 @@ INSTANTIATE_TEST_SUITE_P(InnerType, CreateColumnBySimpleAggregateFunctionType, :
std::make_tuple("SimpleAggregateFunction(anyLast, Tuple(UInt64, String))", "Tuple(UInt64, String)")
));

// The server accepts type aliases (BIGINT, TEXT, ...) and the case-insensitive type names in any letter case
// (see system.data_type_families), so a column can be made from the type name of the table's own DDL.
class CreateColumnByTypeNameAlias
: public ::testing::TestWithParam<std::tuple<const char* /*type*/, const char* /*expected type name*/>>
{};

TEST_P(CreateColumnByTypeNameAlias, CreateColumnByType) {
const auto & [type_name, expected_name] = GetParam();
const auto col = CreateColumnByType(type_name);
ASSERT_NE(nullptr, col) << "CreateColumnByType returned nullptr for " << type_name;
EXPECT_EQ(expected_name, col->GetType().GetName());
}

INSTANTIATE_TEST_SUITE_P(Alias, CreateColumnByTypeNameAlias, ::testing::Values(
std::make_tuple("BIGINT", "Int64"),
std::make_tuple("bigint", "Int64"),
std::make_tuple("TEXT", "String"),
std::make_tuple("VARCHAR(255)", "String"),
std::make_tuple("varchar(255)", "String"),
std::make_tuple("DOUBLE PRECISION", "Float64"),
std::make_tuple("double precision", "Float64"),
std::make_tuple("DOUBLE", "Float64"),
std::make_tuple("FLOAT", "Float32"),
std::make_tuple("INET4", "IPv4"),
std::make_tuple("INET6", "IPv6"),
std::make_tuple("TIMESTAMP", "DateTime"),
std::make_tuple("INT", "Int32"),
std::make_tuple("TINYINT", "Int8"),
std::make_tuple("BINARY(4)", "FixedString(4)"),
std::make_tuple("DEC(9, 2)", "Decimal(9,2)"),
std::make_tuple("NUMERIC(18, 4)", "Decimal(18,4)"),
std::make_tuple("CHARACTER LARGE OBJECT", "String"),
std::make_tuple("NATIONAL CHARACTER LARGE OBJECT", "String"),
std::make_tuple("national char varying", "String")
));

INSTANTIATE_TEST_SUITE_P(SignedUnsigned, CreateColumnByTypeNameAlias, ::testing::Values(
// SIGNED and UNSIGNED are aliases of their own and the last word of 14 multi-word aliases.
std::make_tuple("SIGNED", "Int64"),
std::make_tuple("UNSIGNED", "UInt64"),
std::make_tuple("INT SIGNED", "Int32"),
std::make_tuple("INT UNSIGNED", "UInt32"),
std::make_tuple("int unsigned", "UInt32"),
std::make_tuple("INT1 UNSIGNED", "UInt8"),
std::make_tuple("TINYINT UNSIGNED", "UInt8"),
std::make_tuple("TINYINT SIGNED", "Int8"),
std::make_tuple("SMALLINT UNSIGNED", "UInt16"),
std::make_tuple("SMALLINT SIGNED", "Int16"),
std::make_tuple("MEDIUMINT UNSIGNED", "UInt32"),
std::make_tuple("INTEGER UNSIGNED", "UInt32"),
std::make_tuple("BIGINT UNSIGNED", "UInt64"),
std::make_tuple("BIGINT SIGNED", "Int64")
));

INSTANTIATE_TEST_SUITE_P(LetterCase, CreateColumnByTypeNameAlias, ::testing::Values(
std::make_tuple("datetime", "DateTime"),
std::make_tuple("DATETIME", "DateTime"),
std::make_tuple("datetime('UTC')", "DateTime('UTC')"),
std::make_tuple("DATETIME64(3, 'UTC')", "DateTime64(3, 'UTC')"),
std::make_tuple("date", "Date"),
std::make_tuple("DATE", "Date"),
std::make_tuple("date32", "Date32"),
std::make_tuple("decimal(9, 2)", "Decimal(9,2)"),
std::make_tuple("DECIMAL32(2)", "Decimal(9,2)"),
std::make_tuple("decimal64(2)", "Decimal(18,2)"),
std::make_tuple("Decimal128(2)", "Decimal(38,2)"),
std::make_tuple("json", "JSON"),
std::make_tuple("time", "Time"),
std::make_tuple("TIME64(3)", "Time64(3)"),
std::make_tuple("ARRAY(Int8)", "Array(Int8)"),
std::make_tuple("array(array(INT))", "Array(Array(Int32))"),
std::make_tuple("MAP(String, Int8)", "Map(String, Int8)"),
std::make_tuple("ENUM8('a' = 1)", "Enum8('a' = 1)"),
std::make_tuple("enum16('a' = 1)", "Enum16('a' = 1)")
));

INSTANTIATE_TEST_SUITE_P(Nested, CreateColumnByTypeNameAlias, ::testing::Values(
std::make_tuple("Nullable(BIGINT)", "Nullable(Int64)"),
std::make_tuple("Nullable(INT UNSIGNED)", "Nullable(UInt32)"),
std::make_tuple("Array(TEXT)", "Array(String)"),
std::make_tuple("Map(TEXT, BIGINT)", "Map(String, Int64)"),
std::make_tuple("LowCardinality(TEXT)", "LowCardinality(String)"),
std::make_tuple("Tuple(BIGINT, TEXT)", "Tuple(Int64, String)"),
std::make_tuple("Tuple(a INT UNSIGNED, b DOUBLE PRECISION)", "Tuple(a UInt32, b Float64)"),
std::make_tuple("Tuple(bigint BIGINT, text TEXT)", "Tuple(bigint Int64, text String)")
));

TEST(CreateColumnByType, TypeNameAliasUnknownNames) {
// The server rejects these: only some type families are case-insensitive.
for (const char* name : {"int64", "INT64", "string", "STRING", "uuid", "ipv4", "float64", "fixedstring(3)",
"NULLABLE(Int8)", "nullable(Int8)", "TUPLE(Int8)", "LOWCARDINALITY(String)",
"DOUBLE PRECISION PRECISION", "BINARY LARGE", "NATIONAL"}) {
EXPECT_EQ(nullptr, CreateColumnByType(name)) << name;
}
}

TEST(CreateColumnByType, BoolAlias) {
for (const char* name : {"BOOLEAN", "boolean", "BOOL", "bool", "Bool"}) {
const auto col = CreateColumnByType(name);
ASSERT_NE(nullptr, col) << name;
#if CH_MAP_BOOL_TO_UINT8
EXPECT_EQ(Type::UInt8, col->GetType().GetCode()) << name;
#else
EXPECT_EQ(Type::Bool, col->GetType().GetCode()) << name;
#endif
}
}

TEST(CreateColumnByType, UnmatchedBrackets) {
// When type string has unmatched brackets, CreateColumnByType must return nullptr.
ASSERT_EQ(nullptr, CreateColumnByType("FixedString(10"));
Expand Down
43 changes: 43 additions & 0 deletions ut/client_ut.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include <clickhouse/client.h>
#include <clickhouse/columns/bool.h>
#include <clickhouse/columns/factory.h>

#include "clickhouse/base/socket.h"
#include "clickhouse/types/bignum.h"
Expand Down Expand Up @@ -1024,6 +1025,48 @@ TEST_P(ClientCase, EscapeRoundtrip_Enum) {
EXPECT_EQ(enum_items.size(), row);
}

TEST_P(ClientCase, TypeNameAliasesFromTypeName) {
// Columns made from the type names of the DDL, written with aliases and in another letter case.
client_->Execute(
"CREATE TEMPORARY TABLE IF NOT EXISTS "
"test_clickhouse_cpp_type_alias (id BIGINT, name TEXT, n INT UNSIGNED, f DOUBLE PRECISION, t datetime)");

auto id = CreateColumnByType("BIGINT");
auto name = CreateColumnByType("TEXT");
auto n = CreateColumnByType("INT UNSIGNED");
auto f = CreateColumnByType("DOUBLE PRECISION");
auto t = CreateColumnByType("datetime");
ASSERT_NE(nullptr, id);
ASSERT_NE(nullptr, name);
ASSERT_NE(nullptr, n);
ASSERT_NE(nullptr, f);
ASSERT_NE(nullptr, t);
id->As<ColumnInt64>()->Append(-5);
name->As<ColumnString>()->Append("abc");
n->As<ColumnUInt32>()->Append(4000000000u);
f->As<ColumnFloat64>()->Append(1.5);
t->As<ColumnDateTime>()->Append(86400);

Block b;
b.AppendColumn("id", id);
b.AppendColumn("name", name);
b.AppendColumn("n", n);
b.AppendColumn("f", f);
b.AppendColumn("t", t);
client_->Insert("test_clickhouse_cpp_type_alias", b);

size_t rows = 0;
client_->Select("SELECT id, name, n, f, toUnixTimestamp(t) FROM test_clickhouse_cpp_type_alias", [&rows](const Block& block) {
for (size_t i = 0; i < block.GetRowCount(); ++i, ++rows) {
EXPECT_EQ(-5, (*block[0]->As<ColumnInt64>())[i]);
EXPECT_EQ("abc", block[1]->As<ColumnString>()->At(i));
EXPECT_EQ(4000000000u, (*block[2]->As<ColumnUInt32>())[i]);
EXPECT_EQ(1.5, (*block[3]->As<ColumnFloat64>())[i]);
}
});
EXPECT_EQ(1u, rows);
}

TEST_P(ClientCase, Decimal) {
client_->Execute(
"CREATE TEMPORARY TABLE IF NOT EXISTS "
Expand Down
Loading