ColumnUnique.h 20.2 KB
Newer Older
1
#pragma once
2
#include <Columns/IColumnUnique.h>
3 4
#include <Columns/ReverseIndex.h>

5 6
#include <Columns/ColumnVector.h>
#include <Columns/ColumnNullable.h>
7
#include <Columns/ColumnString.h>
8
#include <Columns/ColumnFixedString.h>
9

N
Nikolai Kochetov 已提交
10
#include <DataTypes/DataTypeNullable.h>
11
#include <DataTypes/NumberTraits.h>
12

13 14
#include <Common/typeid_cast.h>
#include <ext/range.h>
15

A
Alexey Milovidov 已提交
16 17 18
#include <common/unaligned.h>


19 20 21
namespace DB
{

P
proller 已提交
22 23 24 25
namespace ErrorCodes
{
    extern const int ILLEGAL_COLUMN;
}
26

27 28
template <typename ColumnType>
class ColumnUnique final : public COWPtrHelper<IColumnUnique, ColumnUnique<ColumnType>>
29
{
30
    friend class COWPtrHelper<IColumnUnique, ColumnUnique<ColumnType>>;
31 32

private:
33
    explicit ColumnUnique(MutableColumnPtr && holder, bool is_nullable);
34
    explicit ColumnUnique(const IDataType & type);
35
    ColumnUnique(const ColumnUnique & other);
36

37
public:
38 39 40
    MutableColumnPtr cloneEmpty() const override;

    const ColumnPtr & getNestedColumn() const override;
41
    const ColumnPtr & getNestedNotNullableColumn() const override { return column_holder; }
42
    bool nestedColumnIsNullable() const override { return is_nullable; }
43

44 45
    size_t uniqueInsert(const Field & x) override;
    size_t uniqueInsertFrom(const IColumn & src, size_t n) override;
46 47 48
    MutableColumnPtr uniqueInsertRangeFrom(const IColumn & src, size_t start, size_t length) override;
    IColumnUnique::IndexesWithOverflow uniqueInsertRangeWithOverflow(const IColumn & src, size_t start, size_t length,
                                                                     size_t max_dictionary_size) override;
49 50
    size_t uniqueInsertData(const char * pos, size_t length) override;
    size_t uniqueDeserializeAndInsertFromArena(const char * pos, const char *& new_pos) override;
51

52
    size_t getDefaultValueIndex() const override { return 0; }
53
    size_t getNullValueIndex() const override;
54
    size_t getNestedTypeDefaultValueIndex() const override { return is_nullable ? 1 : 0; }
55 56
    bool canContainNulls() const override { return is_nullable; }

57 58 59
    Field operator[](size_t n) const override { return (*getNestedColumn())[n]; }
    void get(size_t n, Field & res) const override { getNestedColumn()->get(n, res); }
    StringRef getDataAt(size_t n) const override { return getNestedColumn()->getDataAt(n); }
N
Nikolai Kochetov 已提交
60 61
    StringRef getDataAtWithTerminatingZero(size_t n) const override
    {
62
        return getNestedColumn()->getDataAtWithTerminatingZero(n);
N
Nikolai Kochetov 已提交
63
    }
64 65 66
    UInt64 get64(size_t n) const override { return getNestedColumn()->get64(n); }
    UInt64 getUInt(size_t n) const override { return getNestedColumn()->getUInt(n); }
    Int64 getInt(size_t n) const override { return getNestedColumn()->getInt(n); }
67
    bool isNullAt(size_t n) const override { return is_nullable && n == getNullValueIndex(); }
68
    StringRef serializeValueIntoArena(size_t n, Arena & arena, char const *& begin) const override;
N
Nikolai Kochetov 已提交
69 70
    void updateHashWithValue(size_t n, SipHash & hash) const override
    {
71
        return getNestedColumn()->updateHashWithValue(n, hash);
N
Nikolai Kochetov 已提交
72
    }
73

74
    int compareAt(size_t n, size_t m, const IColumn & rhs, int nan_direction_hint) const override;
75

76 77 78 79 80 81 82
    void getExtremes(Field & min, Field & max) const override { column_holder->getExtremes(min, max); }
    bool valuesHaveFixedSize() const override { return column_holder->valuesHaveFixedSize(); }
    bool isFixedAndContiguous() const override { return column_holder->isFixedAndContiguous(); }
    size_t sizeOfValueIfFixed() const override { return column_holder->sizeOfValueIfFixed(); }
    bool isNumeric() const override { return column_holder->isNumeric(); }

    size_t byteSize() const override { return column_holder->byteSize(); }
N
Nikolai Kochetov 已提交
83 84
    size_t allocatedBytes() const override
    {
85
        return column_holder->allocatedBytes()
86
               + index.allocatedBytes()
87
               + (nested_null_mask ? nested_null_mask->allocatedBytes() : 0);
88 89 90
    }
    void forEachSubcolumn(IColumn::ColumnCallback callback) override
    {
91
        callback(column_holder);
92
        index.setColumn(getRawColumnPtr());
93 94
        if (is_nullable)
            nested_column_nullable = ColumnNullable::create(column_holder, nested_null_mask);
N
Nikolai Kochetov 已提交
95
    }
96

97 98
    const UInt64 * tryGetSavedHash() const override { return index.tryGetSavedHash(); }

99 100
    UInt128 getHash() const override { return hash.getHash(*getRawColumnPtr()); }

101 102
private:

103
    ColumnPtr column_holder;
104
    bool is_nullable;
105
    size_t size_of_value_if_fixed = 0;
106
    ReverseIndex<UInt64, ColumnType> index;
N
Nikolai Kochetov 已提交
107

108
    /// For DataTypeNullable, stores null map.
109 110
    ColumnPtr nested_null_mask;
    ColumnPtr nested_column_nullable;
N
Nikolai Kochetov 已提交
111

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    class IncrementalHash
    {
    private:
        UInt128 hash;
        std::atomic<size_t> num_added_rows;

        std::mutex mutex;
    public:
        IncrementalHash() : num_added_rows(0) {}

        UInt128 getHash(const ColumnType & column);
    };

    mutable IncrementalHash hash;

127
    void createNullMask();
128 129
    void updateNullMask();

130 131
    static size_t numSpecialValues(bool is_nullable) { return is_nullable ? 2 : 1; }
    size_t numSpecialValues() const { return numSpecialValues(is_nullable); }
132

133
    ColumnType * getRawColumnPtr() { return static_cast<ColumnType *>(column_holder->assumeMutable().get()); }
134
    const ColumnType * getRawColumnPtr() const { return static_cast<const ColumnType *>(column_holder.get()); }
135

136 137
    template <typename IndexType>
    MutableColumnPtr uniqueInsertRangeImpl(
138 139 140
        const IColumn & src,
        size_t start,
        size_t length,
141
        size_t num_added_rows,
142
        typename ColumnVector<IndexType>::MutablePtr && positions_column,
143
        ReverseIndex<UInt64, ColumnType> * secondary_index,
144
        size_t max_dictionary_size);
145 146
};

147 148 149 150 151 152
template <typename ColumnType>
MutableColumnPtr ColumnUnique<ColumnType>::cloneEmpty() const
{
    return ColumnUnique<ColumnType>::create(column_holder->cloneResized(numSpecialValues()), is_nullable);
}

153
template <typename ColumnType>
154 155 156
ColumnUnique<ColumnType>::ColumnUnique(const ColumnUnique & other)
    : column_holder(other.column_holder)
    , is_nullable(other.is_nullable)
157
    , size_of_value_if_fixed (other.size_of_value_if_fixed)
158 159 160
    , index(numSpecialValues(is_nullable), 0)
{
    index.setColumn(getRawColumnPtr());
161
    createNullMask();
162 163 164 165 166 167
}

template <typename ColumnType>
ColumnUnique<ColumnType>::ColumnUnique(const IDataType & type)
    : is_nullable(type.isNullable())
    , index(numSpecialValues(is_nullable), 0)
N
Nikolai Kochetov 已提交
168
{
169 170
    const auto & holder_type = is_nullable ? *static_cast<const DataTypeNullable &>(type).getNestedType() : type;
    column_holder = holder_type.createColumn()->cloneResized(numSpecialValues());
171
    index.setColumn(getRawColumnPtr());
172
    createNullMask();
173 174 175

    if (column_holder->valuesHaveFixedSize())
        size_of_value_if_fixed = column_holder->sizeOfValueIfFixed();
N
Nikolai Kochetov 已提交
176 177
}

178 179
template <typename ColumnType>
ColumnUnique<ColumnType>::ColumnUnique(MutableColumnPtr && holder, bool is_nullable)
180 181 182
    : column_holder(std::move(holder))
    , is_nullable(is_nullable)
    , index(numSpecialValues(is_nullable), 0)
183
{
184 185
    if (column_holder->size() < numSpecialValues())
        throw Exception("Too small holder column for ColumnUnique.", ErrorCodes::ILLEGAL_COLUMN);
186
    if (column_holder->isColumnNullable())
187
        throw Exception("Holder column for ColumnUnique can't be nullable.", ErrorCodes::ILLEGAL_COLUMN);
188 189

    index.setColumn(getRawColumnPtr());
190
    createNullMask();
191 192 193

    if (column_holder->valuesHaveFixedSize())
        size_of_value_if_fixed = column_holder->sizeOfValueIfFixed();
194 195
}

196
template <typename ColumnType>
197
void ColumnUnique<ColumnType>::createNullMask()
N
Nikolai Kochetov 已提交
198 199 200
{
    if (is_nullable)
    {
201
        size_t size = getRawColumnPtr()->size();
202
        if (!nested_null_mask)
203 204 205
        {
            ColumnUInt8::MutablePtr null_mask = ColumnUInt8::create(size, UInt8(0));
            null_mask->getData()[getNullValueIndex()] = 1;
206 207
            nested_null_mask = std::move(null_mask);
            nested_column_nullable = ColumnNullable::create(column_holder, nested_null_mask);
208
        }
209 210 211 212 213 214 215 216 217 218 219 220 221 222
        else
            throw Exception("Null mask for ColumnUnique is already created.", ErrorCodes::LOGICAL_ERROR);
    }
}

template <typename ColumnType>
void ColumnUnique<ColumnType>::updateNullMask()
{
    if (is_nullable)
    {
        if (!nested_null_mask)
            throw Exception("Null mask for ColumnUnique is was not created.", ErrorCodes::LOGICAL_ERROR);

        size_t size = getRawColumnPtr()->size();
223

224
        if (nested_null_mask->size() != size)
225
        {
226 227
            IColumn & null_mask = nested_null_mask->assumeMutableRef();
            static_cast<ColumnUInt8 &>(null_mask).getData().resize_fill(size);
228
        }
N
Nikolai Kochetov 已提交
229
    }
230 231 232 233 234 235 236 237
}

template <typename ColumnType>
const ColumnPtr & ColumnUnique<ColumnType>::getNestedColumn() const
{
    if (is_nullable)
        return nested_column_nullable;

N
Nikolai Kochetov 已提交
238 239 240
    return column_holder;
}

241 242
template <typename ColumnType>
size_t ColumnUnique<ColumnType>::getNullValueIndex() const
243 244
{
    if (!is_nullable)
245
        throw Exception("ColumnUnique can't contain null values.", ErrorCodes::LOGICAL_ERROR);
246 247 248 249

    return 0;
}

250 251
template <typename ColumnType>
size_t ColumnUnique<ColumnType>::uniqueInsert(const Field & x)
252 253 254 255
{
    if (x.getType() == Field::Types::Null)
        return getNullValueIndex();

256 257
    if (size_of_value_if_fixed)
        return uniqueInsertData(&x.get<char>(), size_of_value_if_fixed);
258

259 260
    auto & val = x.get<String>();
    return uniqueInsertData(val.data(), val.size());
261 262
}

263 264
template <typename ColumnType>
size_t ColumnUnique<ColumnType>::uniqueInsertFrom(const IColumn & src, size_t n)
265
{
266 267 268
    if (is_nullable && src.isNullAt(n))
        return getNullValueIndex();

269 270 271
    if (auto * nullable = typeid_cast<const ColumnNullable *>(&src))
        return uniqueInsertFrom(nullable->getNestedColumn(), n);

272 273 274 275
    auto ref = src.getDataAt(n);
    return uniqueInsertData(ref.data, ref.size);
}

276 277
template <typename ColumnType>
size_t ColumnUnique<ColumnType>::uniqueInsertData(const char * pos, size_t length)
278 279 280
{
    auto column = getRawColumnPtr();

281 282
    if (column->getDataAt(getNestedTypeDefaultValueIndex()) == StringRef(pos, length))
        return getNestedTypeDefaultValueIndex();
283

284
    auto insertion_point = index.insert(StringRef(pos, length));
285

286 287
    updateNullMask();

288
    return insertion_point;
289 290
}

291 292 293 294 295 296 297 298 299 300 301 302 303 304
template <typename ColumnType>
StringRef ColumnUnique<ColumnType>::serializeValueIntoArena(size_t n, Arena & arena, char const *& begin) const
{
    if (is_nullable)
    {
        const UInt8 null_flag = 1;
        const UInt8 not_null_flag = 0;

        auto pos = arena.allocContinue(sizeof(null_flag), begin);
        auto & flag = (n == getNullValueIndex() ? null_flag : not_null_flag);
        memcpy(pos, &flag, sizeof(flag));

        size_t nested_size = 0;

305
        if (n != getNullValueIndex())
306 307 308 309 310 311 312 313
            nested_size = column_holder->serializeValueIntoArena(n, arena, begin).size;

        return StringRef(pos, sizeof(null_flag) + nested_size);
    }

    return column_holder->serializeValueIntoArena(n, arena, begin);
}

314 315
template <typename ColumnType>
size_t ColumnUnique<ColumnType>::uniqueDeserializeAndInsertFromArena(const char * pos, const char *& new_pos)
316
{
317 318 319 320 321 322 323 324 325 326 327 328
    if (is_nullable)
    {
        UInt8 val = *reinterpret_cast<const UInt8 *>(pos);
        pos += sizeof(val);

        if (val)
        {
            new_pos = pos;
            return getNullValueIndex();
        }
    }

N
Nikolai Kochetov 已提交
329
    /// Numbers, FixedString
330
    if (size_of_value_if_fixed)
331
    {
332 333
        new_pos = pos + size_of_value_if_fixed;
        return uniqueInsertData(pos, size_of_value_if_fixed);
334 335
    }

N
Nikolai Kochetov 已提交
336
    /// String
A
Alexey Milovidov 已提交
337
    const size_t string_size = unalignedLoad<size_t>(pos);
338 339
    pos += sizeof(string_size);
    new_pos = pos + string_size;
340

N
Nikolai Kochetov 已提交
341 342
    /// -1 because of terminating zero
    return uniqueInsertData(pos, string_size - 1);
343 344
}

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
template <typename ColumnType>
int ColumnUnique<ColumnType>::compareAt(size_t n, size_t m, const IColumn & rhs, int nan_direction_hint) const
{
    if (is_nullable)
    {
        /// See ColumnNullable::compareAt
        bool lval_is_null = n == getNullValueIndex();
        bool rval_is_null = m == getNullValueIndex();

        if (unlikely(lval_is_null || rval_is_null))
        {
            if (lval_is_null && rval_is_null)
                return 0;
            else
                return lval_is_null ? nan_direction_hint : -nan_direction_hint;
        }
    }

    auto & column_unique = static_cast<const IColumnUnique &>(rhs);
    return getNestedColumn()->compareAt(n, m, *column_unique.getNestedColumn(), nan_direction_hint);
}

367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
template <typename IndexType>
static void checkIndexes(const ColumnVector<IndexType> & indexes, size_t max_dictionary_size)
{
    auto & data = indexes.getData();
    for (size_t i = 0; i < data.size(); ++i)
    {
        if (data[i] >= max_dictionary_size)
        {
            throw Exception("Found index " + toString(data[i]) + " at position " + toString(i)
                            + " which is grated or equal than dictionary size " + toString(max_dictionary_size),
                            ErrorCodes::LOGICAL_ERROR);
        }
    }
}

382 383 384
template <typename ColumnType>
template <typename IndexType>
MutableColumnPtr ColumnUnique<ColumnType>::uniqueInsertRangeImpl(
385 386 387
    const IColumn & src,
    size_t start,
    size_t length,
388
    size_t num_added_rows,
389
    typename ColumnVector<IndexType>::MutablePtr && positions_column,
390
    ReverseIndex<UInt64, ColumnType> * secondary_index,
391
    size_t max_dictionary_size)
392 393 394
{
    const ColumnType * src_column;
    const NullMap * null_map = nullptr;
395 396
    auto & positions = positions_column->getData();

397
    auto update_position = [&](UInt64 & next_position) -> MutableColumnPtr
398
    {
399 400 401
        constexpr auto next_size = NumberTraits::nextSize(sizeof(IndexType));
        using SuperiorIndexType = typename NumberTraits::Construct<false, false, next_size>::Type;

402 403 404 405 406 407 408 409
        ++next_position;

        if (next_position > std::numeric_limits<IndexType>::max())
        {
            if (sizeof(SuperiorIndexType) == sizeof(IndexType))
                throw Exception("Can't find superior index type for type " + demangle(typeid(IndexType).name()),
                                ErrorCodes::LOGICAL_ERROR);

410
            auto expanded_column = ColumnVector<SuperiorIndexType>::create(length);
411 412 413 414 415 416
            auto & expanded_data = expanded_column->getData();
            for (size_t i = 0; i < num_added_rows; ++i)
                expanded_data[i] = positions[i];

            return uniqueInsertRangeImpl<SuperiorIndexType>(
                    src,
417 418 419
                    start,
                    length,
                    num_added_rows,
420
                    std::move(expanded_column),
421
                    secondary_index,
422 423 424 425 426
                    max_dictionary_size);
        }

        return nullptr;
    };
427

428
    if (auto nullable_column = typeid_cast<const ColumnNullable *>(&src))
429
    {
430
        src_column = typeid_cast<const ColumnType *>(&nullable_column->getNestedColumn());
431 432 433
        null_map = &nullable_column->getNullMapData();
    }
    else
434
        src_column = typeid_cast<const ColumnType *>(&src);
435

436 437 438
    if (src_column == nullptr)
        throw Exception("Invalid column type for ColumnUnique::insertRangeFrom. Expected " + column_holder->getName() +
                        ", got " + src.getName(), ErrorCodes::ILLEGAL_COLUMN);
439

440 441
    auto column = getRawColumnPtr();

442
    UInt64 next_position = column->size();
443 444 445
    if (secondary_index)
        next_position += secondary_index->size();

446
    auto insert_key = [&](const StringRef & ref, ReverseIndex<UInt64, ColumnType> & cur_index) -> MutableColumnPtr
447
    {
448 449 450 451
        auto inserted_pos = cur_index.insert(ref);
        positions[num_added_rows] = inserted_pos;
        if (inserted_pos == next_position)
            return update_position(next_position);
452

453
        return nullptr;
454 455
    };

456
    for (; num_added_rows < length; ++num_added_rows)
457
    {
458
        auto row = start + num_added_rows;
459

N
Nikolai Kochetov 已提交
460
        if (null_map && (*null_map)[row])
461
            positions[num_added_rows] = getNullValueIndex();
462 463
        else if (column->compareAt(getNestedTypeDefaultValueIndex(), row, *src_column, 1) == 0)
            positions[num_added_rows] = getNestedTypeDefaultValueIndex();
464 465
        else
        {
466
            auto ref = src_column->getDataAt(row);
467
            MutableColumnPtr res = nullptr;
468

469
            if (secondary_index && next_position >= max_dictionary_size)
470
            {
471 472 473
                auto insertion_point = index.getInsertionPoint(ref);
                if (insertion_point == index.lastInsertionPoint())
                    res = insert_key(ref, *secondary_index);
474
                else
475
                    positions[num_added_rows] = insertion_point;
476
            }
477 478 479 480 481
            else
                res = insert_key(ref, index);

            if (res)
                return res;
482 483
        }
    }
484

485
    // checkIndexes(*positions_column, column->size() + (overflowed_keys ? overflowed_keys->size() : 0));
486
    return std::move(positions_column);
487 488
}

489 490
template <typename ColumnType>
MutableColumnPtr ColumnUnique<ColumnType>::uniqueInsertRangeFrom(const IColumn & src, size_t start, size_t length)
491
{
492
    auto callForType = [this, &src, start, length](auto x) -> MutableColumnPtr
493
    {
494 495
        size_t size = getRawColumnPtr()->size();

496 497 498
        using IndexType = decltype(x);
        if (size <= std::numeric_limits<IndexType>::max())
        {
499
            auto positions = ColumnVector<IndexType>::create(length);
500
            return this->uniqueInsertRangeImpl<IndexType>(src, start, length, 0, std::move(positions), nullptr, 0);
501
        }
502

503 504 505 506 507 508 509 510 511 512 513 514 515 516
        return nullptr;
    };

    MutableColumnPtr positions_column;
    if (!positions_column)
        positions_column = callForType(UInt8());
    if (!positions_column)
        positions_column = callForType(UInt16());
    if (!positions_column)
        positions_column = callForType(UInt32());
    if (!positions_column)
        positions_column = callForType(UInt64());
    if (!positions_column)
        throw Exception("Can't find index type for ColumnUnique", ErrorCodes::LOGICAL_ERROR);
517

518 519
    updateNullMask();

520 521 522
    return positions_column;
}

523 524
template <typename ColumnType>
IColumnUnique::IndexesWithOverflow ColumnUnique<ColumnType>::uniqueInsertRangeWithOverflow(
525 526 527 528 529 530 531 532 533 534
    const IColumn & src,
    size_t start,
    size_t length,
    size_t max_dictionary_size)
{
    auto overflowed_keys = column_holder->cloneEmpty();
    auto overflowed_keys_ptr = typeid_cast<ColumnType *>(overflowed_keys.get());
    if (!overflowed_keys_ptr)
        throw Exception("Invalid keys type for ColumnUnique.", ErrorCodes::LOGICAL_ERROR);

535
    auto callForType = [this, &src, start, length, overflowed_keys_ptr, max_dictionary_size](auto x) -> MutableColumnPtr
536
    {
537 538
        size_t size = getRawColumnPtr()->size();

539 540 541
        using IndexType = decltype(x);
        if (size <= std::numeric_limits<IndexType>::max())
        {
542
            auto positions = ColumnVector<IndexType>::create(length);
543 544
            ReverseIndex<UInt64, ColumnType> secondary_index(0, max_dictionary_size);
            secondary_index.setColumn(overflowed_keys_ptr);
545
            return this->uniqueInsertRangeImpl<IndexType>(src, start, length, 0, std::move(positions),
546
                                                          &secondary_index, max_dictionary_size);
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562
        }

        return nullptr;
    };

    MutableColumnPtr positions_column;
    if (!positions_column)
        positions_column = callForType(UInt8());
    if (!positions_column)
        positions_column = callForType(UInt16());
    if (!positions_column)
        positions_column = callForType(UInt32());
    if (!positions_column)
        positions_column = callForType(UInt64());
    if (!positions_column)
        throw Exception("Can't find index type for ColumnUnique", ErrorCodes::LOGICAL_ERROR);
563

564 565
    updateNullMask();

566 567 568 569 570 571
    IColumnUnique::IndexesWithOverflow indexes_with_overflow;
    indexes_with_overflow.indexes = std::move(positions_column);
    indexes_with_overflow.overflowed_keys = std::move(overflowed_keys);
    return indexes_with_overflow;
}

572 573 574 575
template <typename ColumnType>
UInt128 ColumnUnique<ColumnType>::IncrementalHash::getHash(const ColumnType & column)
{
    size_t column_size = column.size();
576
    UInt128 cur_hash;
577 578 579 580 581 582 583 584

    if (column_size != num_added_rows.load())
    {
        SipHash sip_hash;
        for (size_t i = 0; i < column_size; ++i)
            column.updateHashWithValue(i, sip_hash);

        std::lock_guard lock(mutex);
585 586 587 588 589 590 591 592
        sip_hash.get128(hash.low, hash.high);
        cur_hash = hash;
        num_added_rows.store(column_size);
    }
    else
    {
        std::lock_guard lock(mutex);
        cur_hash = hash;
593 594 595 596 597
    }

    return cur_hash;
}

598
}