StorageSet.cpp 7.2 KB
Newer Older
1
#include <Storages/StorageSet.h>
2
#include <Storages/StorageFactory.h>
3
#include <IO/ReadBufferFromFile.h>
P
proller 已提交
4
#include <Compression/CompressedReadBuffer.h>
5
#include <IO/WriteBufferFromFile.h>
P
proller 已提交
6
#include <Compression/CompressedWriteBuffer.h>
7 8
#include <DataStreams/NativeBlockOutputStream.h>
#include <DataStreams/NativeBlockInputStream.h>
A
Alexey Milovidov 已提交
9
#include <Common/formatReadable.h>
10
#include <Common/escapeForFileName.h>
11
#include <Common/StringUtils/StringUtils.h>
12
#include <Interpreters/Set.h>
13
#include <Interpreters/Context.h>
14
#include <Poco/DirectoryIterator.h>
15 16 17 18 19


namespace DB
{

20 21 22 23 24
namespace ErrorCodes
{
    extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH;
}

25

26 27 28 29 30 31
namespace ErrorCodes
{
    extern const int INCORRECT_FILE_NAME;
}


A
Alexey Milovidov 已提交
32 33 34
class SetOrJoinBlockOutputStream : public IBlockOutputStream
{
public:
35 36 37 38
    SetOrJoinBlockOutputStream(
        StorageSetOrJoinBase & table_, const StorageMetadataPtr & metadata_snapshot_,
        const String & backup_path_, const String & backup_tmp_path_,
        const String & backup_file_name_);
A
Alexey Milovidov 已提交
39

40
    Block getHeader() const override { return metadata_snapshot->getSampleBlock(); }
41 42
    void write(const Block & block) override;
    void writeSuffix() override;
A
Alexey Milovidov 已提交
43 44

private:
45
    StorageSetOrJoinBase & table;
46
    StorageMetadataPtr metadata_snapshot;
47 48 49 50 51 52
    String backup_path;
    String backup_tmp_path;
    String backup_file_name;
    WriteBufferFromFile backup_buf;
    CompressedWriteBuffer compressed_backup_buf;
    NativeBlockOutputStream backup_stream;
A
Alexey Milovidov 已提交
53 54 55
};


56 57 58 59 60 61 62 63 64 65 66 67 68 69
SetOrJoinBlockOutputStream::SetOrJoinBlockOutputStream(
    StorageSetOrJoinBase & table_,
    const StorageMetadataPtr & metadata_snapshot_,
    const String & backup_path_,
    const String & backup_tmp_path_,
    const String & backup_file_name_)
    : table(table_)
    , metadata_snapshot(metadata_snapshot_)
    , backup_path(backup_path_)
    , backup_tmp_path(backup_tmp_path_)
    , backup_file_name(backup_file_name_)
    , backup_buf(backup_tmp_path + backup_file_name)
    , compressed_backup_buf(backup_buf)
    , backup_stream(compressed_backup_buf, 0, metadata_snapshot->getSampleBlock())
70
{
71
}
72

73 74
void SetOrJoinBlockOutputStream::write(const Block & block)
{
75 76
    /// Sort columns in the block. This is necessary, since Set and Join count on the same column order in different blocks.
    Block sorted_block = block.sortColumns();
77

78 79
    table.insertBlock(sorted_block);
    backup_stream.write(sorted_block);
80
}
81

82 83
void SetOrJoinBlockOutputStream::writeSuffix()
{
84
    table.finishInsert();
85 86 87
    backup_stream.flush();
    compressed_backup_buf.next();
    backup_buf.next();
88

89
    Poco::File(backup_tmp_path + backup_file_name).renameTo(backup_path + backup_file_name);
90
}
91 92


93
BlockOutputStreamPtr StorageSetOrJoinBase::write(const ASTPtr & /*query*/, const StorageMetadataPtr & metadata_snapshot, const Context & /*context*/)
94
{
95
    UInt64 id = ++increment;
96
    return std::make_shared<SetOrJoinBlockOutputStream>(*this, metadata_snapshot, path, path + "tmp/", toString(id) + ".bin");
97 98 99
}


100
StorageSetOrJoinBase::StorageSetOrJoinBase(
A
Alexander Tokmakov 已提交
101
    const String & relative_path_,
102
    const StorageID & table_id_,
A
Alexey Milovidov 已提交
103
    const ColumnsDescription & columns_,
A
Alexander Tokmakov 已提交
104 105
    const ConstraintsDescription & constraints_,
    const Context & context_)
106
    : IStorage(table_id_)
107
{
108 109 110 111 112
    StorageInMemoryMetadata metadata_;
    metadata_.setColumns(columns_);
    metadata_.setConstraints(constraints_);
    setInMemoryMetadata(metadata_);

A
Alexey Milovidov 已提交
113

A
Alexander Tokmakov 已提交
114
    if (relative_path_.empty())
115 116
        throw Exception("Join and Set storages require data path", ErrorCodes::INCORRECT_FILE_NAME);

117 118
    base_path = context_.getPath();
    path = base_path + relative_path_;
119 120 121 122
}


StorageSet::StorageSet(
A
Alexander Tokmakov 已提交
123
    const String & relative_path_,
124
    const StorageID & table_id_,
A
Alexey Milovidov 已提交
125
    const ColumnsDescription & columns_,
A
Alexander Tokmakov 已提交
126 127
    const ConstraintsDescription & constraints_,
    const Context & context_)
128
    : StorageSetOrJoinBase{relative_path_, table_id_, columns_, constraints_, context_},
129
    set(std::make_shared<Set>(SizeLimits(), false, true))
130
{
131 132

    Block header = getInMemoryMetadataPtr()->getSampleBlock();
133 134 135
    header = header.sortColumns();
    set->setHeader(header);

136
    restore();
137 138 139
}


A
Alexey Milovidov 已提交
140
void StorageSet::insertBlock(const Block & block) { set->insertFromBlock(block); }
141
void StorageSet::finishInsert() { set->finishInsert(); }
Z
zhang2014 已提交
142 143
size_t StorageSet::getSize() const { return set->getTotalRowCount(); }

144

A
alesapin 已提交
145
void StorageSet::truncate(const ASTPtr &, const StorageMetadataPtr & metadata_snapshot, const Context &, TableExclusiveLockHolder &)
Z
zhang2014 已提交
146
{
147 148 149 150
    Poco::File(path).remove(true);
    Poco::File(path).createDirectories();
    Poco::File(path + "tmp/").createDirectories();

151
    Block header = metadata_snapshot->getSampleBlock();
152
    header = header.sortColumns();
153

Z
zhang2014 已提交
154
    increment = 0;
155
    set = std::make_shared<Set>(SizeLimits(), false, true);
156
    set->setHeader(header);
157
}
158 159


160
void StorageSetOrJoinBase::restore()
161
{
162 163 164 165 166 167 168
    Poco::File tmp_dir(path + "tmp/");
    if (!tmp_dir.exists())
    {
        tmp_dir.createDirectories();
        return;
    }

A
Alexey Milovidov 已提交
169
    static const char * file_suffix = ".bin";
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    static const auto file_suffix_size = strlen(".bin");

    Poco::DirectoryIterator dir_end;
    for (Poco::DirectoryIterator dir_it(path); dir_end != dir_it; ++dir_it)
    {
        const auto & name = dir_it.name();

        if (dir_it->isFile()
            && endsWith(name, file_suffix)
            && dir_it->getSize() > 0)
        {
            /// Calculate the maximum number of available files with a backup to add the following files with large numbers.
            UInt64 file_num = parse<UInt64>(name.substr(0, name.size() - file_suffix_size));
            if (file_num > increment)
                increment = file_num;

            restoreFromFile(dir_it->path());
        }
    }
189 190 191
}


192
void StorageSetOrJoinBase::restoreFromFile(const String & file_path)
193
{
194 195
    ReadBufferFromFile backup_buf(file_path);
    CompressedReadBuffer compressed_backup_buf(backup_buf);
196
    NativeBlockInputStream backup_stream(compressed_backup_buf, 0);
197 198

    backup_stream.readPrefix();
199

200 201
    while (Block block = backup_stream.read())
        insertBlock(block);
202 203

    finishInsert();
204 205 206
    backup_stream.readSuffix();

    /// TODO Add speed, compressed bytes, data volume in memory, compression ratio ... Generalize all statistics logging in project.
A
Alexey Milovidov 已提交
207
    LOG_INFO(&Poco::Logger::get("StorageSetOrJoinBase"), "Loaded from backup file {}. {} rows, {}. State has {} unique rows.",
208
        file_path, backup_stream.getProfileInfo().rows, ReadableSize(backup_stream.getProfileInfo().bytes), getSize());
209 210 211
}


A
Alexander Tokmakov 已提交
212
void StorageSetOrJoinBase::rename(const String & new_path_to_table_data, const StorageID & new_table_id)
213
{
214
    /// Rename directory with data.
215
    String new_path = base_path + new_path_to_table_data;
216
    Poco::File(path).renameTo(new_path);
217

A
Alexander Tokmakov 已提交
218
    path = new_path;
A
Alexander Tokmakov 已提交
219
    renameInMemory(new_table_id);
220 221 222
}


223 224 225 226 227 228 229 230 231
void registerStorageSet(StorageFactory & factory)
{
    factory.registerStorage("Set", [](const StorageFactory::Arguments & args)
    {
        if (!args.engine_args.empty())
            throw Exception(
                "Engine " + args.engine_name + " doesn't support any arguments (" + toString(args.engine_args.size()) + " given)",
                ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

232
        return StorageSet::create(args.relative_data_path, args.table_id, args.columns, args.constraints, args.context);
233 234 235 236
    });
}


237
}