StorageJoin.cpp 16.7 KB
Newer Older
1
#include <Storages/StorageJoin.h>
2
#include <Storages/StorageFactory.h>
3
#include <Interpreters/HashJoin.h>
4
#include <Interpreters/Context.h>
A
Amos Bird 已提交
5
#include <Parsers/ASTCreateQuery.h>
6
#include <Parsers/ASTSetQuery.h>
7
#include <Parsers/ASTIdentifier.h>
A
Amos Bird 已提交
8
#include <Core/ColumnNumbers.h>
9
#include <DataStreams/IBlockInputStream.h>
A
Amos Bird 已提交
10
#include <DataTypes/NestedUtils.h>
11
#include <Interpreters/joinDispatch.h>
12
#include <Interpreters/TableJoin.h>
13
#include <Common/assert_cast.h>
A
alexey-milovidov 已提交
14
#include <Common/quoteString.h>
15

16
#include <Poco/String.h>    /// toLower
17
#include <Poco/File.h>
18 19
#include <Processors/Sources/SourceWithProgress.h>
#include <Processors/Pipe.h>
20 21 22 23 24


namespace DB
{

25 26
namespace ErrorCodes
{
A
Alexey Milovidov 已提交
27 28
    extern const int NOT_IMPLEMENTED;
    extern const int LOGICAL_ERROR;
C
chertus 已提交
29
    extern const int UNSUPPORTED_JOIN_KEYS;
30 31
    extern const int NO_SUCH_COLUMN_IN_TABLE;
    extern const int INCOMPATIBLE_TYPE_OF_JOIN;
32 33
    extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
    extern const int BAD_ARGUMENTS;
34 35
}

36
StorageJoin::StorageJoin(
A
Alexander Tokmakov 已提交
37
    const String & relative_path_,
38
    const StorageID & table_id_,
39
    const Names & key_names_,
A
Amos Bird 已提交
40 41 42 43
    bool use_nulls_,
    SizeLimits limits_,
    ASTTableJoin::Kind kind_,
    ASTTableJoin::Strictness strictness_,
44
    const ColumnsDescription & columns_,
A
Alexey Milovidov 已提交
45
    const ConstraintsDescription & constraints_,
46
    bool overwrite_,
A
Alexander Tokmakov 已提交
47
    const Context & context_)
48
    : StorageSetOrJoinBase{relative_path_, table_id_, columns_, constraints_, context_}
A
Amos Bird 已提交
49 50 51 52 53
    , key_names(key_names_)
    , use_nulls(use_nulls_)
    , limits(limits_)
    , kind(kind_)
    , strictness(strictness_)
54
    , overwrite(overwrite_)
55
{
56
    auto metadata_snapshot = getInMemoryMetadataPtr();
57
    for (const auto & key : key_names)
58
        if (!metadata_snapshot->getColumns().hasPhysical(key))
59
            throw Exception{"Key column (" + key + ") does not exist in table declaration.", ErrorCodes::NO_SUCH_COLUMN_IN_TABLE};
60

61
    table_join = std::make_shared<TableJoin>(limits, use_nulls, kind, strictness, key_names);
62
    join = std::make_shared<HashJoin>(table_join, metadata_snapshot->getSampleBlock().sortColumns(), overwrite);
63
    restore();
64 65 66
}


67
void StorageJoin::truncate(const ASTPtr &, const Context &, TableStructureWriteLockHolder &)
68
{
69 70
    /// TODO(alesap) FIXME
    auto metadata_snapshot = getInMemoryMetadataPtr();
71 72
    Poco::File(path).remove(true);
    Poco::File(path).createDirectories();
73
    Poco::File(path + "tmp/").createDirectories();
74 75

    increment = 0;
76
    join = std::make_shared<HashJoin>(table_join, metadata_snapshot->getSampleBlock().sortColumns(), overwrite);
77
}
78 79


80
HashJoinPtr StorageJoin::getJoin(std::shared_ptr<TableJoin> analyzed_join) const
81
{
82
    auto metadata_snapshot = getInMemoryMetadataPtr();
C
chertus 已提交
83
    if (!analyzed_join->sameStrictnessAndKind(strictness, kind))
A
Alexander Tokmakov 已提交
84
        throw Exception("Table " + getStorageID().getNameForLogs() + " has incompatible type of JOIN.", ErrorCodes::INCOMPATIBLE_TYPE_OF_JOIN);
C
chertus 已提交
85

C
chertus 已提交
86 87
    if ((analyzed_join->forceNullableRight() && !use_nulls) ||
        (!analyzed_join->forceNullableRight() && isLeftOrFull(analyzed_join->kind()) && use_nulls))
88
        throw Exception("Table " + getStorageID().getNameForLogs() + " needs the same join_use_nulls setting as present in LEFT or FULL JOIN.",
89 90
                        ErrorCodes::INCOMPATIBLE_TYPE_OF_JOIN);

C
chertus 已提交
91 92
    /// TODO: check key columns

93 94 95
    /// Some HACK to remove wrong names qualifiers: table.column -> column.
    analyzed_join->setRightKeys(key_names);

96
    HashJoinPtr join_clone = std::make_shared<HashJoin>(analyzed_join, metadata_snapshot->getSampleBlock().sortColumns());
C
chertus 已提交
97 98
    join_clone->reuseJoinedData(*join);
    return join_clone;
99 100 101
}


102
void StorageJoin::insertBlock(const Block & block) { join->addJoinedBlock(block, true); }
103
size_t StorageJoin::getSize() const { return join->getTotalRowCount(); }
104

105 106 107

void registerStorageJoin(StorageFactory & factory)
{
108
    auto creator_fn = [](const StorageFactory::Arguments & args)
109 110 111 112 113
    {
        /// Join(ANY, LEFT, k1, k2, ...)

        ASTs & engine_args = args.engine_args;

A
Alexey Milovidov 已提交
114
        const auto & settings = args.context.getSettingsRef();
115

A
Amos Bird 已提交
116 117 118 119
        auto join_use_nulls = settings.join_use_nulls;
        auto max_rows_in_join = settings.max_rows_in_join;
        auto max_bytes_in_join = settings.max_bytes_in_join;
        auto join_overflow_mode = settings.join_overflow_mode;
120
        auto join_any_take_last_row = settings.join_any_take_last_row;
121
        auto old_any_join = settings.any_join_distinct_right_table_keys;
A
Amos Bird 已提交
122 123 124

        if (args.storage_def && args.storage_def->settings)
        {
125
            for (const auto & setting : args.storage_def->settings->changes)
A
Amos Bird 已提交
126
            {
A
Alexey Milovidov 已提交
127 128 129 130 131 132 133 134
                if (setting.name == "join_use_nulls")
                    join_use_nulls.set(setting.value);
                else if (setting.name == "max_rows_in_join")
                    max_rows_in_join.set(setting.value);
                else if (setting.name == "max_bytes_in_join")
                    max_bytes_in_join.set(setting.value);
                else if (setting.name == "join_overflow_mode")
                    join_overflow_mode.set(setting.value);
135 136
                else if (setting.name == "join_any_take_last_row")
                    join_any_take_last_row.set(setting.value);
137 138
                else if (setting.name == "any_join_distinct_right_table_keys")
                    old_any_join.set(setting.value);
A
Amos Bird 已提交
139 140 141 142 143 144 145
                else
                    throw Exception(
                        "Unknown setting " + setting.name + " for storage " + args.engine_name,
                        ErrorCodes::BAD_ARGUMENTS);
            }
        }

146 147 148 149 150 151 152 153 154 155 156 157
        if (engine_args.size() < 3)
            throw Exception(
                "Storage Join requires at least 3 parameters: Join(ANY|ALL|SEMI|ANTI, LEFT|INNER|RIGHT, keys...).",
                ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

        ASTTableJoin::Strictness strictness = ASTTableJoin::Strictness::Unspecified;
        ASTTableJoin::Kind kind = ASTTableJoin::Kind::Comma;

        if (auto opt_strictness_id = tryGetIdentifierName(engine_args[0]))
        {
            const String strictness_str = Poco::toLower(*opt_strictness_id);

C
chertus 已提交
158
            if (strictness_str == "any")
159 160 161 162 163 164
            {
                if (old_any_join)
                    strictness = ASTTableJoin::Strictness::RightAny;
                else
                    strictness = ASTTableJoin::Strictness::Any;
            }
C
chertus 已提交
165
            else if (strictness_str == "all")
166
                strictness = ASTTableJoin::Strictness::All;
C
chertus 已提交
167
            else if (strictness_str == "semi")
168
                strictness = ASTTableJoin::Strictness::Semi;
C
chertus 已提交
169
            else if (strictness_str == "anti")
170 171 172 173
                strictness = ASTTableJoin::Strictness::Anti;
        }

        if (strictness == ASTTableJoin::Strictness::Unspecified)
C
chertus 已提交
174 175
            throw Exception("First parameter of storage Join must be ANY or ALL or SEMI or ANTI (without quotes).",
                            ErrorCodes::BAD_ARGUMENTS);
176 177 178 179 180

        if (auto opt_kind_id = tryGetIdentifierName(engine_args[1]))
        {
            const String kind_str = Poco::toLower(*opt_kind_id);

C
chertus 已提交
181
            if (kind_str == "left")
182
                kind = ASTTableJoin::Kind::Left;
C
chertus 已提交
183
            else if (kind_str == "inner")
184
                kind = ASTTableJoin::Kind::Inner;
C
chertus 已提交
185
            else if (kind_str == "right")
186
                kind = ASTTableJoin::Kind::Right;
C
chertus 已提交
187
            else if (kind_str == "full")
188 189 190 191 192 193 194 195
            {
                if (strictness == ASTTableJoin::Strictness::Any)
                    strictness = ASTTableJoin::Strictness::RightAny;
                kind = ASTTableJoin::Kind::Full;
            }
        }

        if (kind == ASTTableJoin::Kind::Comma)
C
chertus 已提交
196 197
            throw Exception("Second parameter of storage Join must be LEFT or INNER or RIGHT or FULL (without quotes).",
                            ErrorCodes::BAD_ARGUMENTS);
198 199 200 201 202 203 204 205 206 207 208 209

        Names key_names;
        key_names.reserve(engine_args.size() - 2);
        for (size_t i = 2, size = engine_args.size(); i < size; ++i)
        {
            auto opt_key = tryGetIdentifierName(engine_args[i]);
            if (!opt_key)
                throw Exception("Parameter №" + toString(i + 1) + " of storage Join don't look like column name.", ErrorCodes::BAD_ARGUMENTS);

            key_names.push_back(*opt_key);
        }

210
        return StorageJoin::create(
A
Alexander Tokmakov 已提交
211
            args.relative_data_path,
212
            args.table_id,
A
Amos Bird 已提交
213
            key_names,
A
alesapin 已提交
214 215
            join_use_nulls,
            SizeLimits{max_rows_in_join, max_bytes_in_join, join_overflow_mode},
A
Amos Bird 已提交
216 217
            kind,
            strictness,
218
            args.columns,
A
Alexey Milovidov 已提交
219
            args.constraints,
A
Alexander Tokmakov 已提交
220 221
            join_any_take_last_row,
            args.context);
222 223 224
    };

    factory.registerStorage("Join", creator_fn, StorageFactory::StorageFeatures{ .supports_settings = true, });
225 226
}

A
Amos Bird 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
template <typename T>
static const char * rawData(T & t)
{
    return reinterpret_cast<const char *>(&t);
}
template <typename T>
static size_t rawSize(T &)
{
    return sizeof(T);
}
template <>
const char * rawData(const StringRef & t)
{
    return t.data;
}
template <>
size_t rawSize(const StringRef & t)
{
    return t.size;
}

248
class JoinSource : public SourceWithProgress
A
Amos Bird 已提交
249 250
{
public:
251
    JoinSource(const HashJoin & parent_, UInt64 max_block_size_, Block sample_block_)
252 253 254 255 256
        : SourceWithProgress(sample_block_)
        , parent(parent_)
        , lock(parent.data->rwlock)
        , max_block_size(max_block_size_)
        , sample_block(std::move(sample_block_))
A
Amos Bird 已提交
257 258
    {
        column_indices.resize(sample_block.columns());
A
Artem Zuikov 已提交
259 260 261

        auto & saved_block = parent.getJoinedData()->sample_block;

A
Amos Bird 已提交
262 263 264
        for (size_t i = 0; i < sample_block.columns(); ++i)
        {
            auto & [_, type, name] = sample_block.getByPosition(i);
C
chertus 已提交
265
            if (parent.right_table_keys.has(name))
A
Amos Bird 已提交
266 267
            {
                key_pos = i;
A
Artem Zuikov 已提交
268
                const auto & column = parent.right_table_keys.getByName(name);
A
Artem Zuikov 已提交
269
                restored_block.insert(column);
A
Amos Bird 已提交
270 271 272
            }
            else
            {
A
Artem Zuikov 已提交
273
                size_t pos = saved_block.getPositionByName(name);
A
Amos Bird 已提交
274
                column_indices[i] = pos;
A
Artem Zuikov 已提交
275

A
Artem Zuikov 已提交
276
                const auto & column = saved_block.getByPosition(pos);
A
Artem Zuikov 已提交
277
                restored_block.insert(column);
A
Amos Bird 已提交
278 279 280 281 282 283 284
            }
        }
    }

    String getName() const override { return "Join"; }

protected:
285
    Chunk generate() override
A
Amos Bird 已提交
286
    {
C
chertus 已提交
287
        if (parent.data->blocks.empty())
288
            return {};
A
Amos Bird 已提交
289

290
        Chunk chunk;
C
chertus 已提交
291
        if (!joinDispatch(parent.kind, parent.strictness, parent.data->maps,
292
                [&](auto kind, auto strictness, auto & map) { chunk = createChunk<kind, strictness>(map); }))
293
            throw Exception("Logical error: unknown JOIN strictness", ErrorCodes::LOGICAL_ERROR);
294
        return chunk;
A
Amos Bird 已提交
295 296 297
    }

private:
298
    const HashJoin & parent;
A
Amos Bird 已提交
299
    std::shared_lock<std::shared_mutex> lock;
A
Alexey Milovidov 已提交
300
    UInt64 max_block_size;
A
Amos Bird 已提交
301
    Block sample_block;
A
Artem Zuikov 已提交
302
    Block restored_block; /// sample_block with parent column types
A
Amos Bird 已提交
303 304 305 306 307 308 309

    ColumnNumbers column_indices;
    std::optional<size_t> key_pos;

    std::unique_ptr<void, std::function<void(void *)>> position; /// type erasure


310
    template <ASTTableJoin::Kind KIND, ASTTableJoin::Strictness STRICTNESS, typename Maps>
311
    Chunk createChunk(const Maps & maps)
A
Amos Bird 已提交
312
    {
A
Artem Zuikov 已提交
313
        MutableColumns columns = restored_block.cloneEmpty().mutateColumns();
A
Amos Bird 已提交
314 315 316

        size_t rows_added = 0;

C
chertus 已提交
317
        switch (parent.data->type)
A
Amos Bird 已提交
318 319
        {
#define M(TYPE)                                           \
320
    case HashJoin::Type::TYPE:                                \
A
Artem Zuikov 已提交
321
        rows_added = fillColumns<KIND, STRICTNESS>(*maps.TYPE, columns); \
A
Amos Bird 已提交
322 323 324 325 326
        break;
            APPLY_FOR_JOIN_VARIANTS_LIMITED(M)
#undef M

            default:
C
chertus 已提交
327
                throw Exception("Unsupported JOIN keys in StorageJoin. Type: " + toString(static_cast<UInt32>(parent.data->type)),
C
chertus 已提交
328
                                ErrorCodes::UNSUPPORTED_JOIN_KEYS);
A
Amos Bird 已提交
329 330 331 332 333
        }

        if (!rows_added)
            return {};

A
Artem Zuikov 已提交
334
        /// Correct nullability
A
Amos Bird 已提交
335
        for (size_t i = 0; i < columns.size(); ++i)
A
Artem Zuikov 已提交
336 337 338 339 340
        {
            bool src_nullable = restored_block.getByPosition(i).type->isNullable();
            bool dst_nullable = sample_block.getByPosition(i).type->isNullable();

            if (src_nullable && !dst_nullable)
A
Amos Bird 已提交
341
            {
A
Artem Zuikov 已提交
342 343
                auto & nullable_column = assert_cast<ColumnNullable &>(*columns[i]);
                columns[i] = nullable_column.getNestedColumnPtr()->assumeMutable();
A
Amos Bird 已提交
344
            }
A
Artem Zuikov 已提交
345 346 347
            else if (!src_nullable && dst_nullable)
                columns[i] = makeNullable(std::move(columns[i]))->assumeMutable();
        }
A
Amos Bird 已提交
348

A
Artem Zuikov 已提交
349 350
        UInt64 num_rows = columns.at(0)->size();
        return Chunk(std::move(columns), num_rows);
A
Amos Bird 已提交
351 352
    }

353
    template <ASTTableJoin::Kind KIND, ASTTableJoin::Strictness STRICTNESS, typename Map>
A
Artem Zuikov 已提交
354
    size_t fillColumns(const Map & map, MutableColumns & columns)
A
Amos Bird 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367
    {
        size_t rows_added = 0;

        if (!position)
            position = decltype(position)(
                static_cast<void *>(new typename Map::const_iterator(map.begin())),
                [](void * ptr) { delete reinterpret_cast<typename Map::const_iterator *>(ptr); });

        auto & it = *reinterpret_cast<typename Map::const_iterator *>(position.get());
        auto end = map.end();

        for (; it != end; ++it)
        {
368
            if constexpr (STRICTNESS == ASTTableJoin::Strictness::RightAny)
A
Amos Bird 已提交
369
            {
370 371 372 373 374
                fillOne<Map>(columns, column_indices, it, key_pos, rows_added);
            }
            else if constexpr (STRICTNESS == ASTTableJoin::Strictness::All)
            {
                fillAll<Map>(columns, column_indices, it, key_pos, rows_added);
A
Amos Bird 已提交
375
            }
376 377
            else if constexpr (STRICTNESS == ASTTableJoin::Strictness::Any)
            {
378 379 380 381 382 383 384 385 386 387 388
                if constexpr (KIND == ASTTableJoin::Kind::Left || KIND == ASTTableJoin::Kind::Inner)
                    fillOne<Map>(columns, column_indices, it, key_pos, rows_added);
                else if constexpr (KIND == ASTTableJoin::Kind::Right)
                    fillAll<Map>(columns, column_indices, it, key_pos, rows_added);
            }
            else if constexpr (STRICTNESS == ASTTableJoin::Strictness::Semi)
            {
                if constexpr (KIND == ASTTableJoin::Kind::Left)
                    fillOne<Map>(columns, column_indices, it, key_pos, rows_added);
                else if constexpr (KIND == ASTTableJoin::Kind::Right)
                    fillAll<Map>(columns, column_indices, it, key_pos, rows_added);
389
            }
390
            else if constexpr (STRICTNESS == ASTTableJoin::Strictness::Anti)
391
            {
392 393 394 395
                if constexpr (KIND == ASTTableJoin::Kind::Left)
                    fillOne<Map>(columns, column_indices, it, key_pos, rows_added);
                else if constexpr (KIND == ASTTableJoin::Kind::Right)
                    fillAll<Map>(columns, column_indices, it, key_pos, rows_added);
396
            }
A
Amos Bird 已提交
397
            else
398
                throw Exception("This JOIN is not implemented yet", ErrorCodes::NOT_IMPLEMENTED);
A
Amos Bird 已提交
399 400 401 402 403 404 405 406 407 408

            if (rows_added >= max_block_size)
            {
                ++it;
                break;
            }
        }

        return rows_added;
    }
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435

    template <typename Map>
    static void fillOne(MutableColumns & columns, const ColumnNumbers & column_indices, typename Map::const_iterator & it,
                        const std::optional<size_t> & key_pos, size_t & rows_added)
    {
        for (size_t j = 0; j < columns.size(); ++j)
            if (j == key_pos)
                columns[j]->insertData(rawData(it->getKey()), rawSize(it->getKey()));
            else
                columns[j]->insertFrom(*it->getMapped().block->getByPosition(column_indices[j]).column.get(), it->getMapped().row_num);
        ++rows_added;
    }

    template <typename Map>
    static void fillAll(MutableColumns & columns, const ColumnNumbers & column_indices, typename Map::const_iterator & it,
                        const std::optional<size_t> & key_pos, size_t & rows_added)
    {
        for (auto ref_it = it->getMapped().begin(); ref_it.ok(); ++ref_it)
        {
            for (size_t j = 0; j < columns.size(); ++j)
                if (j == key_pos)
                    columns[j]->insertData(rawData(it->getKey()), rawSize(it->getKey()));
                else
                    columns[j]->insertFrom(*ref_it->block->getByPosition(column_indices[j]).column.get(), ref_it->row_num);
            ++rows_added;
        }
    }
A
Amos Bird 已提交
436 437 438 439
};


// TODO: multiple stream read and index read
440
Pipes StorageJoin::read(
A
Amos Bird 已提交
441
    const Names & column_names,
442
    const StorageMetadataPtr & metadata_snapshot,
A
Amos Bird 已提交
443 444 445
    const SelectQueryInfo & /*query_info*/,
    const Context & /*context*/,
    QueryProcessingStage::Enum /*processed_stage*/,
446
    size_t max_block_size,
A
Amos Bird 已提交
447 448
    unsigned /*num_streams*/)
{
A
alesapin 已提交
449
    metadata_snapshot->check(column_names, getVirtuals());
450 451

    Pipes pipes;
452
    pipes.emplace_back(std::make_shared<JoinSource>(*join, max_block_size, metadata_snapshot->getSampleBlockForColumns(column_names, getVirtuals())));
453 454

    return pipes;
A
Amos Bird 已提交
455 456
}

457
}