1#include <Storages/MergeTree/MergeTreeMutationEntry.h>
2#include <IO/Operators.h>
3#include <IO/WriteBufferFromFile.h>
4#include <IO/ReadBufferFromFile.h>
5#include <IO/ReadBufferFromString.h>
6
7#include <Poco/File.h>
8#include <Poco/Path.h>
9
10
11namespace DB
12{
13
14MergeTreeMutationEntry::MergeTreeMutationEntry(MutationCommands commands_, const String & path_prefix_, Int64 tmp_number)
15 : create_time(time(nullptr))
16 , commands(std::move(commands_))
17 , path_prefix(path_prefix_)
18 , file_name("tmp_mutation_" + toString(tmp_number) + ".txt")
19 , is_temp(true)
20{
21 try
22 {
23 WriteBufferFromFile out(path_prefix + file_name);
24 out << "format version: 1\n"
25 << "create time: " << LocalDateTime(create_time) << "\n";
26 out << "commands: ";
27 commands.writeText(out);
28 out << "\n";
29 out.sync();
30 }
31 catch (...)
32 {
33 removeFile();
34 throw;
35 }
36}
37
38void MergeTreeMutationEntry::commit(Int64 block_number_)
39{
40 block_number = block_number_;
41 String new_file_name = "mutation_" + toString(block_number) + ".txt";
42 Poco::File(path_prefix + file_name).renameTo(path_prefix + new_file_name);
43 is_temp = false;
44 file_name = new_file_name;
45}
46
47void MergeTreeMutationEntry::removeFile()
48{
49 if (!file_name.empty())
50 {
51 Poco::File file(path_prefix + file_name);
52 if (!file.exists())
53 return;
54
55 file.remove(false);
56 file_name.clear();
57 }
58}
59
60MergeTreeMutationEntry::MergeTreeMutationEntry(const String & path_prefix_, const String & file_name_)
61 : path_prefix(path_prefix_)
62 , file_name(file_name_)
63 , is_temp(false)
64{
65 ReadBufferFromString file_name_buf(file_name);
66 file_name_buf >> "mutation_" >> block_number >> ".txt";
67 assertEOF(file_name_buf);
68
69 ReadBufferFromFile buf(path_prefix + file_name);
70
71 buf >> "format version: 1\n";
72
73 LocalDateTime create_time_dt;
74 buf >> "create time: " >> create_time_dt >> "\n";
75 create_time = create_time_dt;
76
77 buf >> "commands: ";
78 commands.readText(buf);
79 buf >> "\n";
80
81 assertEOF(buf);
82
83}
84
85MergeTreeMutationEntry::~MergeTreeMutationEntry()
86{
87 if (is_temp && startsWith(file_name, "tmp_"))
88 {
89 try
90 {
91 removeFile();
92 }
93 catch (...)
94 {
95 tryLogCurrentException(__PRETTY_FUNCTION__);
96 }
97 }
98}
99
100}
101