Heap.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. * Copyright (c) 2023, Jelle Raaijmakers <jelle@gmta.nl>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/DeprecatedString.h>
  8. #include <AK/Format.h>
  9. #include <AK/QuickSort.h>
  10. #include <LibCore/System.h>
  11. #include <LibSQL/Heap.h>
  12. #include <sys/stat.h>
  13. namespace SQL {
  14. Heap::Heap(DeprecatedString file_name)
  15. {
  16. set_name(move(file_name));
  17. }
  18. Heap::~Heap()
  19. {
  20. if (m_file && !m_write_ahead_log.is_empty()) {
  21. if (auto maybe_error = flush(); maybe_error.is_error())
  22. warnln("~Heap({}): {}", name(), maybe_error.error());
  23. }
  24. }
  25. ErrorOr<void> Heap::open()
  26. {
  27. size_t file_size = 0;
  28. struct stat stat_buffer;
  29. if (stat(name().characters(), &stat_buffer) != 0) {
  30. if (errno != ENOENT) {
  31. warnln("Heap::open({}): could not stat: {}"sv, name(), strerror(errno));
  32. return Error::from_string_literal("Heap::open(): could not stat file");
  33. }
  34. } else if (!S_ISREG(stat_buffer.st_mode)) {
  35. warnln("Heap::open({}): can only use regular files"sv, name());
  36. return Error::from_string_literal("Heap::open(): can only use regular files");
  37. } else {
  38. file_size = stat_buffer.st_size;
  39. }
  40. if (file_size > 0) {
  41. m_next_block = file_size / Block::SIZE;
  42. m_highest_block_written = m_next_block - 1;
  43. }
  44. auto file = TRY(Core::File::open(name(), Core::File::OpenMode::ReadWrite));
  45. m_file = TRY(Core::InputBufferedFile::create(move(file)));
  46. if (file_size > 0) {
  47. if (auto error_maybe = read_zero_block(); error_maybe.is_error()) {
  48. m_file = nullptr;
  49. return error_maybe.release_error();
  50. }
  51. } else {
  52. TRY(initialize_zero_block());
  53. }
  54. // FIXME: We should more gracefully handle version incompatibilities. For now, we drop the database.
  55. if (m_version != VERSION) {
  56. dbgln_if(SQL_DEBUG, "Heap file {} opened has incompatible version {}. Deleting for version {}.", name(), m_version, VERSION);
  57. m_file = nullptr;
  58. TRY(Core::System::unlink(name()));
  59. return open();
  60. }
  61. dbgln_if(SQL_DEBUG, "Heap file {} opened; number of blocks = {}", name(), m_highest_block_written);
  62. return {};
  63. }
  64. bool Heap::has_block(Block::Index index) const
  65. {
  66. return index <= m_highest_block_written || m_write_ahead_log.contains(index);
  67. }
  68. ErrorOr<ByteBuffer> Heap::read_storage(Block::Index index)
  69. {
  70. dbgln_if(SQL_DEBUG, "{}({})", __FUNCTION__, index);
  71. // Reconstruct the data storage from a potential chain of blocks
  72. ByteBuffer data;
  73. while (index > 0) {
  74. auto block = TRY(read_block(index));
  75. dbgln_if(SQL_DEBUG, " -> {} bytes", block.size_in_bytes());
  76. TRY(data.try_append(block.data().bytes().slice(0, block.size_in_bytes())));
  77. index = block.next_block();
  78. }
  79. return data;
  80. }
  81. ErrorOr<void> Heap::write_storage(Block::Index index, ReadonlyBytes data)
  82. {
  83. dbgln_if(SQL_DEBUG, "{}({}, {} bytes)", __FUNCTION__, index, data.size());
  84. VERIFY(data.size() > 0);
  85. // Split up the storage across multiple blocks if necessary, creating a chain
  86. u32 remaining_size = static_cast<u32>(data.size());
  87. u32 offset_in_data = 0;
  88. while (remaining_size > 0) {
  89. auto block_data_size = AK::min(remaining_size, Block::DATA_SIZE);
  90. remaining_size -= block_data_size;
  91. auto next_block_index = (remaining_size > 0) ? request_new_block_index() : 0;
  92. auto block_data = TRY(ByteBuffer::create_uninitialized(block_data_size));
  93. block_data.bytes().overwrite(0, data.offset(offset_in_data), block_data_size);
  94. TRY(write_block({ index, block_data_size, next_block_index, move(block_data) }));
  95. index = next_block_index;
  96. offset_in_data += block_data_size;
  97. }
  98. return {};
  99. }
  100. ErrorOr<ByteBuffer> Heap::read_raw_block(Block::Index index)
  101. {
  102. VERIFY(m_file);
  103. VERIFY(index < m_next_block);
  104. if (auto data = m_write_ahead_log.get(index); data.has_value())
  105. return data.value();
  106. TRY(m_file->seek(index * Block::SIZE, SeekMode::SetPosition));
  107. auto buffer = TRY(ByteBuffer::create_uninitialized(Block::SIZE));
  108. TRY(m_file->read_until_filled(buffer));
  109. return buffer;
  110. }
  111. ErrorOr<Block> Heap::read_block(Block::Index index)
  112. {
  113. dbgln_if(SQL_DEBUG, "Read heap block {}", index);
  114. auto buffer = TRY(read_raw_block(index));
  115. auto size_in_bytes = *reinterpret_cast<u32*>(buffer.offset_pointer(0));
  116. auto next_block = *reinterpret_cast<Block::Index*>(buffer.offset_pointer(sizeof(u32)));
  117. auto data = TRY(buffer.slice(Block::HEADER_SIZE, Block::DATA_SIZE));
  118. return Block { index, size_in_bytes, next_block, move(data) };
  119. }
  120. ErrorOr<void> Heap::write_raw_block(Block::Index index, ReadonlyBytes data)
  121. {
  122. dbgln_if(SQL_DEBUG, "Write raw block {}", index);
  123. VERIFY(m_file);
  124. VERIFY(data.size() == Block::SIZE);
  125. TRY(m_file->seek(index * Block::SIZE, SeekMode::SetPosition));
  126. TRY(m_file->write_until_depleted(data));
  127. if (index > m_highest_block_written)
  128. m_highest_block_written = index;
  129. return {};
  130. }
  131. ErrorOr<void> Heap::write_raw_block_to_wal(Block::Index index, ByteBuffer&& data)
  132. {
  133. dbgln_if(SQL_DEBUG, "{}(): adding raw block {} to WAL", __FUNCTION__, index);
  134. VERIFY(index < m_next_block);
  135. VERIFY(data.size() == Block::SIZE);
  136. TRY(m_write_ahead_log.try_set(index, move(data)));
  137. return {};
  138. }
  139. ErrorOr<void> Heap::write_block(Block const& block)
  140. {
  141. VERIFY(block.index() < m_next_block);
  142. VERIFY(block.next_block() < m_next_block);
  143. VERIFY(block.data().size() <= Block::DATA_SIZE);
  144. auto size_in_bytes = block.size_in_bytes();
  145. auto next_block = block.next_block();
  146. auto heap_data = TRY(ByteBuffer::create_zeroed(Block::SIZE));
  147. heap_data.overwrite(0, &size_in_bytes, sizeof(size_in_bytes));
  148. heap_data.overwrite(sizeof(size_in_bytes), &next_block, sizeof(next_block));
  149. block.data().bytes().copy_to(heap_data.bytes().slice(Block::HEADER_SIZE));
  150. return write_raw_block_to_wal(block.index(), move(heap_data));
  151. }
  152. ErrorOr<void> Heap::flush()
  153. {
  154. VERIFY(m_file);
  155. auto indices = m_write_ahead_log.keys();
  156. quick_sort(indices);
  157. for (auto index : indices) {
  158. dbgln_if(SQL_DEBUG, "Flushing block {} to {}", index, name());
  159. auto& data = m_write_ahead_log.get(index).value();
  160. TRY(write_raw_block(index, data));
  161. }
  162. m_write_ahead_log.clear();
  163. dbgln_if(SQL_DEBUG, "WAL flushed; new number of blocks = {}", m_highest_block_written);
  164. return {};
  165. }
  166. constexpr static auto FILE_ID = "SerenitySQL "sv;
  167. constexpr static auto VERSION_OFFSET = FILE_ID.length();
  168. constexpr static auto SCHEMAS_ROOT_OFFSET = VERSION_OFFSET + sizeof(u32);
  169. constexpr static auto TABLES_ROOT_OFFSET = SCHEMAS_ROOT_OFFSET + sizeof(u32);
  170. constexpr static auto TABLE_COLUMNS_ROOT_OFFSET = TABLES_ROOT_OFFSET + sizeof(u32);
  171. constexpr static auto USER_VALUES_OFFSET = TABLE_COLUMNS_ROOT_OFFSET + sizeof(u32);
  172. ErrorOr<void> Heap::read_zero_block()
  173. {
  174. dbgln_if(SQL_DEBUG, "Read zero block from {}", name());
  175. auto block = TRY(read_raw_block(0));
  176. auto file_id_buffer = TRY(block.slice(0, FILE_ID.length()));
  177. auto file_id = StringView(file_id_buffer);
  178. if (file_id != FILE_ID) {
  179. warnln("{}: Zero page corrupt. This is probably not a {} heap file"sv, name(), FILE_ID);
  180. return Error::from_string_literal("Heap()::read_zero_block(): Zero page corrupt. This is probably not a SerenitySQL heap file");
  181. }
  182. memcpy(&m_version, block.offset_pointer(VERSION_OFFSET), sizeof(u32));
  183. dbgln_if(SQL_DEBUG, "Version: {}.{}", (m_version & 0xFFFF0000) >> 16, (m_version & 0x0000FFFF));
  184. memcpy(&m_schemas_root, block.offset_pointer(SCHEMAS_ROOT_OFFSET), sizeof(u32));
  185. dbgln_if(SQL_DEBUG, "Schemas root node: {}", m_schemas_root);
  186. memcpy(&m_tables_root, block.offset_pointer(TABLES_ROOT_OFFSET), sizeof(u32));
  187. dbgln_if(SQL_DEBUG, "Tables root node: {}", m_tables_root);
  188. memcpy(&m_table_columns_root, block.offset_pointer(TABLE_COLUMNS_ROOT_OFFSET), sizeof(u32));
  189. dbgln_if(SQL_DEBUG, "Table columns root node: {}", m_table_columns_root);
  190. memcpy(m_user_values.data(), block.offset_pointer(USER_VALUES_OFFSET), m_user_values.size() * sizeof(u32));
  191. for (auto ix = 0u; ix < m_user_values.size(); ix++) {
  192. if (m_user_values[ix])
  193. dbgln_if(SQL_DEBUG, "User value {}: {}", ix, m_user_values[ix]);
  194. }
  195. return {};
  196. }
  197. ErrorOr<void> Heap::update_zero_block()
  198. {
  199. dbgln_if(SQL_DEBUG, "Write zero block to {}", name());
  200. dbgln_if(SQL_DEBUG, "Version: {}.{}", (m_version & 0xFFFF0000) >> 16, (m_version & 0x0000FFFF));
  201. dbgln_if(SQL_DEBUG, "Schemas root node: {}", m_schemas_root);
  202. dbgln_if(SQL_DEBUG, "Tables root node: {}", m_tables_root);
  203. dbgln_if(SQL_DEBUG, "Table Columns root node: {}", m_table_columns_root);
  204. for (auto ix = 0u; ix < m_user_values.size(); ix++) {
  205. if (m_user_values[ix] > 0)
  206. dbgln_if(SQL_DEBUG, "User value {}: {}", ix, m_user_values[ix]);
  207. }
  208. auto buffer = TRY(ByteBuffer::create_zeroed(Block::SIZE));
  209. auto buffer_bytes = buffer.bytes();
  210. buffer_bytes.overwrite(0, FILE_ID.characters_without_null_termination(), FILE_ID.length());
  211. buffer_bytes.overwrite(VERSION_OFFSET, &m_version, sizeof(u32));
  212. buffer_bytes.overwrite(SCHEMAS_ROOT_OFFSET, &m_schemas_root, sizeof(u32));
  213. buffer_bytes.overwrite(TABLES_ROOT_OFFSET, &m_tables_root, sizeof(u32));
  214. buffer_bytes.overwrite(TABLE_COLUMNS_ROOT_OFFSET, &m_table_columns_root, sizeof(u32));
  215. buffer_bytes.overwrite(USER_VALUES_OFFSET, m_user_values.data(), m_user_values.size() * sizeof(u32));
  216. return write_raw_block_to_wal(0, move(buffer));
  217. }
  218. ErrorOr<void> Heap::initialize_zero_block()
  219. {
  220. m_version = VERSION;
  221. m_schemas_root = 0;
  222. m_tables_root = 0;
  223. m_table_columns_root = 0;
  224. m_next_block = 1;
  225. for (auto& user : m_user_values)
  226. user = 0u;
  227. return update_zero_block();
  228. }
  229. }