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 <Poco/DirectoryIterator.h>
13 14 15 16 17


namespace DB
{

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

23

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


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

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

private:
41 42 43 44 45 46 47
    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 已提交
48 49 50
};


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

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

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

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

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


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


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

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

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


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

121
    restore();
122 123 124
}


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

129

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

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

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


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

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


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

    backup_stream.readPrefix();
184

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

    finishInsert();
189 190 191 192 193 194 195 196
    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.");
197 198 199
}


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

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


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

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


225
}