StorageSet.cpp 6.7 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 9
#include <DataStreams/NativeBlockOutputStream.h>
#include <DataStreams/NativeBlockInputStream.h>
#include <Common/escapeForFileName.h>
10
#include <Common/StringUtils/StringUtils.h>
11
#include <Interpreters/Set.h>
12
#include <Interpreters/Context.h>
13
#include <Poco/DirectoryIterator.h>
14 15 16 17 18


namespace DB
{

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

24

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


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

37
    Block getHeader() const override { return table.getSampleBlock(); }
38 39
    void write(const Block & block) override;
    void writeSuffix() override;
A
Alexey Milovidov 已提交
40 41

private:
42 43 44 45 46 47 48
    StorageSetOrJoinBase & table;
    String backup_path;
    String backup_tmp_path;
    String backup_file_name;
    WriteBufferFromFile backup_buf;
    CompressedWriteBuffer compressed_backup_buf;
    NativeBlockOutputStream backup_stream;
A
Alexey Milovidov 已提交
49 50 51
};


52
SetOrJoinBlockOutputStream::SetOrJoinBlockOutputStream(StorageSetOrJoinBase & table_,
53 54 55 56 57 58
    const String & backup_path_, const String & backup_tmp_path_, const String & backup_file_name_)
    : table(table_),
    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),
59
    backup_stream(compressed_backup_buf, 0, table.getSampleBlock())
60
{
61
}
62

63 64
void SetOrJoinBlockOutputStream::write(const Block & block)
{
65 66
    /// 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();
67

68 69
    table.insertBlock(sorted_block);
    backup_stream.write(sorted_block);
70
}
71

72 73
void SetOrJoinBlockOutputStream::writeSuffix()
{
74
    table.finishInsert();
75 76 77
    backup_stream.flush();
    compressed_backup_buf.next();
    backup_buf.next();
78

79
    Poco::File(backup_tmp_path + backup_file_name).renameTo(backup_path + backup_file_name);
80
}
81 82


83
BlockOutputStreamPtr StorageSetOrJoinBase::write(const ASTPtr & /*query*/, const Context & /*context*/)
84
{
85 86
    UInt64 id = ++increment;
    return std::make_shared<SetOrJoinBlockOutputStream>(*this, path, path + "tmp/", toString(id) + ".bin");
87 88 89
}


90
StorageSetOrJoinBase::StorageSetOrJoinBase(
A
Alexander Tokmakov 已提交
91
    const String & relative_path_,
92
    const StorageID & table_id_,
A
Alexey Milovidov 已提交
93
    const ColumnsDescription & columns_,
A
Alexander Tokmakov 已提交
94 95
    const ConstraintsDescription & constraints_,
    const Context & context_)
96
    : IStorage(table_id_)
97
{
A
Alexey Milovidov 已提交
98 99 100
    setColumns(columns_);
    setConstraints(constraints_);

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

104 105
    base_path = context_.getPath();
    path = base_path + relative_path_;
106 107 108 109
}


StorageSet::StorageSet(
A
Alexander Tokmakov 已提交
110
    const String & relative_path_,
111
    const StorageID & table_id_,
A
Alexey Milovidov 已提交
112
    const ColumnsDescription & columns_,
A
Alexander Tokmakov 已提交
113 114
    const ConstraintsDescription & constraints_,
    const Context & context_)
115
    : StorageSetOrJoinBase{relative_path_, table_id_, columns_, constraints_, context_},
116
    set(std::make_shared<Set>(SizeLimits(), false, true))
117
{
118 119 120 121
    Block header = getSampleBlock();
    header = header.sortColumns();
    set->setHeader(header);

122
    restore();
123 124 125
}


A
Alexey Milovidov 已提交
126
void StorageSet::insertBlock(const Block & block) { set->insertFromBlock(block); }
127
void StorageSet::finishInsert() { set->finishInsert(); }
Z
zhang2014 已提交
128 129
size_t StorageSet::getSize() const { return set->getTotalRowCount(); }

130

131
void StorageSet::truncate(const ASTPtr &, const Context &, TableStructureWriteLockHolder &)
Z
zhang2014 已提交
132
{
133 134 135 136
    Poco::File(path).remove(true);
    Poco::File(path).createDirectories();
    Poco::File(path + "tmp/").createDirectories();

137 138
    Block header = getSampleBlock();
    header = header.sortColumns();
139

Z
zhang2014 已提交
140
    increment = 0;
141
    set = std::make_shared<Set>(SizeLimits(), false, true);
142
    set->setHeader(header);
143
}
144 145


146
void StorageSetOrJoinBase::restore()
147
{
148 149 150 151 152 153 154
    Poco::File tmp_dir(path + "tmp/");
    if (!tmp_dir.exists())
    {
        tmp_dir.createDirectories();
        return;
    }

A
Alexey Milovidov 已提交
155
    static const char * file_suffix = ".bin";
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    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());
        }
    }
175 176 177
}


178
void StorageSetOrJoinBase::restoreFromFile(const String & file_path)
179
{
180 181
    ReadBufferFromFile backup_buf(file_path);
    CompressedReadBuffer compressed_backup_buf(backup_buf);
182
    NativeBlockInputStream backup_stream(compressed_backup_buf, 0);
183 184

    backup_stream.readPrefix();
185

186 187
    while (Block block = backup_stream.read())
        insertBlock(block);
188 189

    finishInsert();
190 191 192 193 194 195 196 197
    backup_stream.readSuffix();

    /// TODO Add speed, compressed bytes, data volume in memory, compression ratio ... Generalize all statistics logging in project.
    LOG_INFO(&Logger::get("StorageSetOrJoinBase"), std::fixed << std::setprecision(2)
        << "Loaded from backup file " << file_path << ". "
        << backup_stream.getProfileInfo().rows << " rows, "
        << backup_stream.getProfileInfo().bytes / 1048576.0 << " MiB. "
        << "State has " << getSize() << " unique rows.");
198 199 200
}


A
Alexander Tokmakov 已提交
201
void StorageSetOrJoinBase::rename(const String & new_path_to_table_data, const StorageID & new_table_id)
202
{
203
    /// Rename directory with data.
204
    String new_path = base_path + new_path_to_table_data;
205
    Poco::File(path).renameTo(new_path);
206

A
Alexander Tokmakov 已提交
207
    path = new_path;
A
Alexander Tokmakov 已提交
208
    renameInMemory(new_table_id);
209 210 211
}


212 213 214 215 216 217 218 219 220
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);

221
        return StorageSet::create(args.relative_data_path, args.table_id, args.columns, args.constraints, args.context);
222 223 224 225
    });
}


226
}