aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Columns/getLeastSuperColumn.cpp
blob: 6ec5ca7a9c10d3f866a61c434b22d7291e70b6b0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <Columns/getLeastSuperColumn.h>
#include <Columns/IColumn.h>
#include <Columns/ColumnConst.h>
#include <Common/assert_cast.h>
#include <DataTypes/getLeastSupertype.h>


namespace DB
{

namespace ErrorCodes
{
    extern const int LOGICAL_ERROR;
}

static bool sameConstants(const IColumn & a, const IColumn & b)
{
    return assert_cast<const ColumnConst &>(a).getField() == assert_cast<const ColumnConst &>(b).getField();
}

ColumnWithTypeAndName getLeastSuperColumn(const std::vector<const ColumnWithTypeAndName *> & columns)
{
    if (columns.empty())
        throw Exception(ErrorCodes::LOGICAL_ERROR, "Logical error: no src columns for supercolumn");

    ColumnWithTypeAndName result = *columns[0];

    /// Determine common type.

    size_t num_const = 0;
    DataTypes types(columns.size());
    for (size_t i = 0; i < columns.size(); ++i)
    {
        types[i] = columns[i]->type;
        if (isColumnConst(*columns[i]->column))
            ++num_const;
    }

    result.type = getLeastSupertype(types);

    /// Create supertype column saving constness if possible.

    bool save_constness = false;
    if (columns.size() == num_const)
    {
        save_constness = true;
        for (size_t i = 1; i < columns.size(); ++i)
        {
            const ColumnWithTypeAndName & first = *columns[0];
            const ColumnWithTypeAndName & other = *columns[i];

            if (!sameConstants(*first.column, *other.column))
            {
                save_constness = false;
                break;
            }
        }
    }

    if (save_constness)
        result.column = result.type->createColumnConst(0, assert_cast<const ColumnConst &>(*columns[0]->column).getField());
    else
        result.column = result.type->createColumn();

    return result;
}

}