Heap.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. VERIFY(!m_file);
  28. size_t file_size = 0;
  29. struct stat stat_buffer;
  30. if (stat(name().characters(), &stat_buffer) != 0) {
  31. if (errno != ENOENT) {
  32. warnln("Heap::open({}): could not stat: {}"sv, name(), strerror(errno));
  33. return Error::from_string_literal("Heap::open(): could not stat file");
  34. }
  35. } else if (!S_ISREG(stat_buffer.st_mode)) {
  36. warnln("Heap::open({}): can only use regular files"sv, name());
  37. return Error::from_string_literal("Heap::open(): can only use regular files");
  38. } else {
  39. file_size = stat_buffer.st_size;
  40. }
  41. if (file_size > 0) {
  42. m_next_block = file_size / Block::SIZE;
  43. m_highest_block_written = m_next_block - 1;
  44. }
  45. auto file = TRY(Core::File::open(name(), Core::File::OpenMode::ReadWrite));
  46. m_file = TRY(Core::InputBufferedFile::create(move(file)));
  47. if (file_size > 0) {
  48. if (auto error_maybe = read_zero_block(); error_maybe.is_error()) {
  49. m_file = nullptr;
  50. return error_maybe.release_error();
  51. }
  52. } else {
  53. TRY(initialize_zero_block());
  54. }
  55. // FIXME: We should more gracefully handle version incompatibilities. For now, we drop the database.
  56. if (m_version != VERSION) {
  57. dbgln_if(SQL_DEBUG, "Heap file {} opened has incompatible version {}. Deleting for version {}.", name(), m_version, VERSION);
  58. m_file = nullptr;
  59. TRY(Core::System::unlink(name()));
  60. return open();
  61. }
  62. // Perform a heap scan to find all free blocks
  63. // FIXME: this is very inefficient; store free blocks in a persistent heap structure
  64. for (Block::Index index = 1; index <= m_highest_block_written; ++index) {
  65. auto block_data = TRY(read_raw_block(index));
  66. auto size_in_bytes = *reinterpret_cast<u32*>(block_data.data());
  67. if (size_in_bytes == 0)
  68. TRY(m_free_block_indices.try_append(index));
  69. }
  70. dbgln_if(SQL_DEBUG, "Heap file {} opened; number of blocks = {}; free blocks = {}", name(), m_highest_block_written, m_free_block_indices.size());
  71. return {};
  72. }
  73. ErrorOr<size_t> Heap::file_size_in_bytes() const
  74. {
  75. TRY(m_file->seek(0, SeekMode::FromEndPosition));
  76. return TRY(m_file->tell());
  77. }
  78. bool Heap::has_block(Block::Index index) const
  79. {
  80. return (index <= m_highest_block_written || m_write_ahead_log.contains(index))
  81. && !m_free_block_indices.contains_slow(index);
  82. }
  83. Block::Index Heap::request_new_block_index()
  84. {
  85. if (!m_free_block_indices.is_empty())
  86. return m_free_block_indices.take_last();
  87. return m_next_block++;
  88. }
  89. ErrorOr<ByteBuffer> Heap::read_storage(Block::Index index)
  90. {
  91. dbgln_if(SQL_DEBUG, "{}({})", __FUNCTION__, index);
  92. // Reconstruct the data storage from a potential chain of blocks
  93. ByteBuffer data;
  94. while (index > 0) {
  95. auto block = TRY(read_block(index));
  96. dbgln_if(SQL_DEBUG, " -> {} bytes", block.size_in_bytes());
  97. TRY(data.try_append(block.data().bytes().slice(0, block.size_in_bytes())));
  98. index = block.next_block();
  99. }
  100. return data;
  101. }
  102. ErrorOr<void> Heap::write_storage(Block::Index index, ReadonlyBytes data)
  103. {
  104. dbgln_if(SQL_DEBUG, "{}({}, {} bytes)", __FUNCTION__, index, data.size());
  105. if (index == 0)
  106. return Error::from_string_view("Writing to zero block is not allowed"sv);
  107. if (data.is_empty())
  108. return Error::from_string_view("Writing empty data is not allowed"sv);
  109. if (m_free_block_indices.contains_slow(index))
  110. return Error::from_string_view("Invalid write to a free block index"sv);
  111. // Split up the storage across multiple blocks if necessary, creating a chain
  112. u32 remaining_size = static_cast<u32>(data.size());
  113. u32 offset_in_data = 0;
  114. Block::Index existing_next_block_index = 0;
  115. while (remaining_size > 0) {
  116. auto block_data_size = AK::min(remaining_size, Block::DATA_SIZE);
  117. remaining_size -= block_data_size;
  118. ByteBuffer block_data;
  119. if (has_block(index)) {
  120. auto existing_block = TRY(read_block(index));
  121. block_data = existing_block.data();
  122. TRY(block_data.try_resize(block_data_size));
  123. existing_next_block_index = existing_block.next_block();
  124. } else {
  125. block_data = TRY(ByteBuffer::create_uninitialized(block_data_size));
  126. existing_next_block_index = 0;
  127. }
  128. Block::Index next_block_index = existing_next_block_index;
  129. if (next_block_index == 0 && remaining_size > 0)
  130. next_block_index = request_new_block_index();
  131. else if (remaining_size == 0)
  132. next_block_index = 0;
  133. block_data.bytes().overwrite(0, data.offset(offset_in_data), block_data_size);
  134. TRY(write_block({ index, block_data_size, next_block_index, move(block_data) }));
  135. index = next_block_index;
  136. offset_in_data += block_data_size;
  137. }
  138. // Free remaining blocks in existing chain, if any
  139. if (existing_next_block_index > 0)
  140. TRY(free_storage(existing_next_block_index));
  141. return {};
  142. }
  143. ErrorOr<ByteBuffer> Heap::read_raw_block(Block::Index index)
  144. {
  145. VERIFY(m_file);
  146. VERIFY(index < m_next_block);
  147. if (auto wal_entry = m_write_ahead_log.get(index); wal_entry.has_value())
  148. return wal_entry.value();
  149. TRY(m_file->seek(index * Block::SIZE, SeekMode::SetPosition));
  150. auto buffer = TRY(ByteBuffer::create_uninitialized(Block::SIZE));
  151. TRY(m_file->read_until_filled(buffer));
  152. return buffer;
  153. }
  154. ErrorOr<Block> Heap::read_block(Block::Index index)
  155. {
  156. dbgln_if(SQL_DEBUG, "{}({})", __FUNCTION__, index);
  157. auto buffer = TRY(read_raw_block(index));
  158. auto size_in_bytes = *reinterpret_cast<u32*>(buffer.offset_pointer(0));
  159. auto next_block = *reinterpret_cast<Block::Index*>(buffer.offset_pointer(sizeof(u32)));
  160. auto data = TRY(buffer.slice(Block::HEADER_SIZE, Block::DATA_SIZE));
  161. return Block { index, size_in_bytes, next_block, move(data) };
  162. }
  163. ErrorOr<void> Heap::write_raw_block(Block::Index index, ReadonlyBytes data)
  164. {
  165. dbgln_if(SQL_DEBUG, "Write raw block {}", index);
  166. VERIFY(m_file);
  167. VERIFY(data.size() == Block::SIZE);
  168. TRY(m_file->seek(index * Block::SIZE, SeekMode::SetPosition));
  169. TRY(m_file->write_until_depleted(data));
  170. if (index > m_highest_block_written)
  171. m_highest_block_written = index;
  172. return {};
  173. }
  174. ErrorOr<void> Heap::write_raw_block_to_wal(Block::Index index, ByteBuffer&& data)
  175. {
  176. dbgln_if(SQL_DEBUG, "{}({})", __FUNCTION__, index);
  177. VERIFY(index < m_next_block);
  178. VERIFY(data.size() == Block::SIZE);
  179. TRY(m_write_ahead_log.try_set(index, move(data)));
  180. return {};
  181. }
  182. ErrorOr<void> Heap::write_block(Block const& block)
  183. {
  184. dbgln_if(SQL_DEBUG, "{}({})", __FUNCTION__, block.index());
  185. VERIFY(block.index() < m_next_block);
  186. VERIFY(block.next_block() < m_next_block);
  187. VERIFY(block.size_in_bytes() > 0);
  188. VERIFY(block.data().size() <= Block::DATA_SIZE);
  189. auto size_in_bytes = block.size_in_bytes();
  190. auto next_block = block.next_block();
  191. auto heap_data = TRY(ByteBuffer::create_zeroed(Block::SIZE));
  192. heap_data.overwrite(0, &size_in_bytes, sizeof(size_in_bytes));
  193. heap_data.overwrite(sizeof(size_in_bytes), &next_block, sizeof(next_block));
  194. block.data().bytes().copy_to(heap_data.bytes().slice(Block::HEADER_SIZE));
  195. return write_raw_block_to_wal(block.index(), move(heap_data));
  196. }
  197. ErrorOr<void> Heap::free_storage(Block::Index index)
  198. {
  199. dbgln_if(SQL_DEBUG, "{}({})", __FUNCTION__, index);
  200. VERIFY(index > 0);
  201. while (index > 0) {
  202. auto block = TRY(read_block(index));
  203. TRY(free_block(block));
  204. index = block.next_block();
  205. }
  206. return {};
  207. }
  208. ErrorOr<void> Heap::free_block(Block const& block)
  209. {
  210. auto index = block.index();
  211. dbgln_if(SQL_DEBUG, "{}({})", __FUNCTION__, index);
  212. VERIFY(index > 0);
  213. VERIFY(has_block(index));
  214. // Zero out freed blocks to facilitate a free block scan upon opening the database later
  215. auto zeroed_data = TRY(ByteBuffer::create_zeroed(Block::SIZE));
  216. TRY(write_raw_block_to_wal(index, move(zeroed_data)));
  217. return m_free_block_indices.try_append(index);
  218. }
  219. ErrorOr<void> Heap::flush()
  220. {
  221. VERIFY(m_file);
  222. auto indices = m_write_ahead_log.keys();
  223. quick_sort(indices);
  224. for (auto index : indices) {
  225. dbgln_if(SQL_DEBUG, "Flushing block {}", index);
  226. auto& data = m_write_ahead_log.get(index).value();
  227. TRY(write_raw_block(index, data));
  228. }
  229. m_write_ahead_log.clear();
  230. dbgln_if(SQL_DEBUG, "WAL flushed; new number of blocks = {}", m_highest_block_written);
  231. return {};
  232. }
  233. constexpr static auto FILE_ID = "SerenitySQL "sv;
  234. constexpr static auto VERSION_OFFSET = FILE_ID.length();
  235. constexpr static auto SCHEMAS_ROOT_OFFSET = VERSION_OFFSET + sizeof(u32);
  236. constexpr static auto TABLES_ROOT_OFFSET = SCHEMAS_ROOT_OFFSET + sizeof(u32);
  237. constexpr static auto TABLE_COLUMNS_ROOT_OFFSET = TABLES_ROOT_OFFSET + sizeof(u32);
  238. constexpr static auto USER_VALUES_OFFSET = TABLE_COLUMNS_ROOT_OFFSET + sizeof(u32);
  239. ErrorOr<void> Heap::read_zero_block()
  240. {
  241. dbgln_if(SQL_DEBUG, "Read zero block from {}", name());
  242. auto block = TRY(read_raw_block(0));
  243. auto file_id_buffer = TRY(block.slice(0, FILE_ID.length()));
  244. auto file_id = StringView(file_id_buffer);
  245. if (file_id != FILE_ID) {
  246. warnln("{}: Zero page corrupt. This is probably not a {} heap file"sv, name(), FILE_ID);
  247. return Error::from_string_literal("Heap()::read_zero_block(): Zero page corrupt. This is probably not a SerenitySQL heap file");
  248. }
  249. memcpy(&m_version, block.offset_pointer(VERSION_OFFSET), sizeof(u32));
  250. dbgln_if(SQL_DEBUG, "Version: {}.{}", (m_version & 0xFFFF0000) >> 16, (m_version & 0x0000FFFF));
  251. memcpy(&m_schemas_root, block.offset_pointer(SCHEMAS_ROOT_OFFSET), sizeof(u32));
  252. dbgln_if(SQL_DEBUG, "Schemas root node: {}", m_schemas_root);
  253. memcpy(&m_tables_root, block.offset_pointer(TABLES_ROOT_OFFSET), sizeof(u32));
  254. dbgln_if(SQL_DEBUG, "Tables root node: {}", m_tables_root);
  255. memcpy(&m_table_columns_root, block.offset_pointer(TABLE_COLUMNS_ROOT_OFFSET), sizeof(u32));
  256. dbgln_if(SQL_DEBUG, "Table columns root node: {}", m_table_columns_root);
  257. memcpy(m_user_values.data(), block.offset_pointer(USER_VALUES_OFFSET), m_user_values.size() * sizeof(u32));
  258. for (auto ix = 0u; ix < m_user_values.size(); ix++) {
  259. if (m_user_values[ix])
  260. dbgln_if(SQL_DEBUG, "User value {}: {}", ix, m_user_values[ix]);
  261. }
  262. return {};
  263. }
  264. ErrorOr<void> Heap::update_zero_block()
  265. {
  266. dbgln_if(SQL_DEBUG, "Write zero block to {}", name());
  267. dbgln_if(SQL_DEBUG, "Version: {}.{}", (m_version & 0xFFFF0000) >> 16, (m_version & 0x0000FFFF));
  268. dbgln_if(SQL_DEBUG, "Schemas root node: {}", m_schemas_root);
  269. dbgln_if(SQL_DEBUG, "Tables root node: {}", m_tables_root);
  270. dbgln_if(SQL_DEBUG, "Table Columns root node: {}", m_table_columns_root);
  271. for (auto ix = 0u; ix < m_user_values.size(); ix++) {
  272. if (m_user_values[ix] > 0)
  273. dbgln_if(SQL_DEBUG, "User value {}: {}", ix, m_user_values[ix]);
  274. }
  275. auto buffer = TRY(ByteBuffer::create_zeroed(Block::SIZE));
  276. auto buffer_bytes = buffer.bytes();
  277. buffer_bytes.overwrite(0, FILE_ID.characters_without_null_termination(), FILE_ID.length());
  278. buffer_bytes.overwrite(VERSION_OFFSET, &m_version, sizeof(u32));
  279. buffer_bytes.overwrite(SCHEMAS_ROOT_OFFSET, &m_schemas_root, sizeof(u32));
  280. buffer_bytes.overwrite(TABLES_ROOT_OFFSET, &m_tables_root, sizeof(u32));
  281. buffer_bytes.overwrite(TABLE_COLUMNS_ROOT_OFFSET, &m_table_columns_root, sizeof(u32));
  282. buffer_bytes.overwrite(USER_VALUES_OFFSET, m_user_values.data(), m_user_values.size() * sizeof(u32));
  283. return write_raw_block_to_wal(0, move(buffer));
  284. }
  285. ErrorOr<void> Heap::initialize_zero_block()
  286. {
  287. m_version = VERSION;
  288. m_schemas_root = 0;
  289. m_tables_root = 0;
  290. m_table_columns_root = 0;
  291. m_next_block = 1;
  292. for (auto& user : m_user_values)
  293. user = 0u;
  294. return update_zero_block();
  295. }
  296. }