Database.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. * Copyright (c) 2021, Mahmoud Mandour <ma.mandourr@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/ByteString.h>
  8. #include <LibSQL/BTree.h>
  9. #include <LibSQL/Database.h>
  10. #include <LibSQL/Heap.h>
  11. #include <LibSQL/Meta.h>
  12. #include <LibSQL/Row.h>
  13. #include <LibSQL/Tuple.h>
  14. namespace SQL {
  15. ErrorOr<NonnullRefPtr<Database>> Database::create(ByteString name)
  16. {
  17. auto heap = TRY(Heap::create(move(name)));
  18. return adopt_nonnull_ref_or_enomem(new (nothrow) Database(move(heap)));
  19. }
  20. Database::Database(NonnullRefPtr<Heap> heap)
  21. : m_heap(move(heap))
  22. , m_serializer(m_heap)
  23. {
  24. }
  25. ResultOr<void> Database::open()
  26. {
  27. VERIFY(!m_open);
  28. TRY(m_heap->open());
  29. m_schemas = TRY(BTree::create(m_serializer, SchemaDef::index_def()->to_tuple_descriptor(), m_heap->schemas_root()));
  30. m_schemas->on_new_root = [&]() {
  31. m_heap->set_schemas_root(m_schemas->root());
  32. };
  33. m_tables = TRY(BTree::create(m_serializer, TableDef::index_def()->to_tuple_descriptor(), m_heap->tables_root()));
  34. m_tables->on_new_root = [&]() {
  35. m_heap->set_tables_root(m_tables->root());
  36. };
  37. m_table_columns = TRY(BTree::create(m_serializer, ColumnDef::index_def()->to_tuple_descriptor(), m_heap->table_columns_root()));
  38. m_table_columns->on_new_root = [&]() {
  39. m_heap->set_table_columns_root(m_table_columns->root());
  40. };
  41. m_open = true;
  42. auto ensure_schema_exists = [&](auto schema_name) -> ResultOr<NonnullRefPtr<SchemaDef>> {
  43. if (auto result = get_schema(schema_name); result.is_error()) {
  44. if (result.error().error() != SQLErrorCode::SchemaDoesNotExist)
  45. return result.release_error();
  46. auto schema_def = TRY(SchemaDef::create(schema_name));
  47. TRY(add_schema(*schema_def));
  48. return schema_def;
  49. } else {
  50. return result.release_value();
  51. }
  52. };
  53. (void)TRY(ensure_schema_exists("default"sv));
  54. auto master_schema = TRY(ensure_schema_exists("master"sv));
  55. if (auto result = get_table("master"sv, "internal_describe_table"sv); result.is_error()) {
  56. if (result.error().error() != SQLErrorCode::TableDoesNotExist)
  57. return result.release_error();
  58. auto internal_describe_table = TRY(TableDef::create(master_schema, "internal_describe_table"));
  59. internal_describe_table->append_column("Name", SQLType::Text);
  60. internal_describe_table->append_column("Type", SQLType::Text);
  61. TRY(add_table(*internal_describe_table));
  62. }
  63. return {};
  64. }
  65. Database::~Database() = default;
  66. ErrorOr<void> Database::commit()
  67. {
  68. VERIFY(is_open());
  69. TRY(m_heap->flush());
  70. return {};
  71. }
  72. ResultOr<void> Database::add_schema(SchemaDef const& schema)
  73. {
  74. VERIFY(is_open());
  75. if (!m_schemas->insert(schema.key()))
  76. return Result { SQLCommand::Unknown, SQLErrorCode::SchemaExists, schema.name() };
  77. return {};
  78. }
  79. Key Database::get_schema_key(ByteString const& schema_name)
  80. {
  81. auto key = SchemaDef::make_key();
  82. key["schema_name"] = schema_name;
  83. return key;
  84. }
  85. ResultOr<NonnullRefPtr<SchemaDef>> Database::get_schema(ByteString const& schema)
  86. {
  87. VERIFY(is_open());
  88. auto schema_name = schema;
  89. if (schema.is_empty())
  90. schema_name = "default"sv;
  91. Key key = get_schema_key(schema_name);
  92. if (auto it = m_schema_cache.find(key.hash()); it != m_schema_cache.end())
  93. return it->value;
  94. auto schema_iterator = m_schemas->find(key);
  95. if (schema_iterator.is_end() || (*schema_iterator != key))
  96. return Result { SQLCommand::Unknown, SQLErrorCode::SchemaDoesNotExist, schema_name };
  97. auto schema_def = TRY(SchemaDef::create(*schema_iterator));
  98. m_schema_cache.set(key.hash(), schema_def);
  99. return schema_def;
  100. }
  101. ResultOr<void> Database::add_table(TableDef& table)
  102. {
  103. VERIFY(is_open());
  104. if (!m_tables->insert(table.key()))
  105. return Result { SQLCommand::Unknown, SQLErrorCode::TableExists, table.name() };
  106. for (auto& column : table.columns()) {
  107. if (!m_table_columns->insert(column->key()))
  108. VERIFY_NOT_REACHED();
  109. }
  110. return {};
  111. }
  112. Key Database::get_table_key(ByteString const& schema_name, ByteString const& table_name)
  113. {
  114. auto key = TableDef::make_key(get_schema_key(schema_name));
  115. key["table_name"] = table_name;
  116. return key;
  117. }
  118. ResultOr<NonnullRefPtr<TableDef>> Database::get_table(ByteString const& schema, ByteString const& name)
  119. {
  120. VERIFY(is_open());
  121. auto schema_name = schema;
  122. if (schema.is_empty())
  123. schema_name = "default"sv;
  124. Key key = get_table_key(schema_name, name);
  125. if (auto it = m_table_cache.find(key.hash()); it != m_table_cache.end())
  126. return it->value;
  127. auto table_iterator = m_tables->find(key);
  128. if (table_iterator.is_end() || (*table_iterator != key))
  129. return Result { SQLCommand::Unknown, SQLErrorCode::TableDoesNotExist, ByteString::formatted("{}.{}", schema_name, name) };
  130. auto schema_def = TRY(get_schema(schema));
  131. auto table_def = TRY(TableDef::create(schema_def, name));
  132. table_def->set_block_index((*table_iterator).block_index());
  133. m_table_cache.set(key.hash(), table_def);
  134. auto table_hash = table_def->hash();
  135. auto column_key = ColumnDef::make_key(table_def);
  136. for (auto it = m_table_columns->find(column_key); !it.is_end() && ((*it)["table_hash"].to_int<u32>() == table_hash); ++it)
  137. table_def->append_column(*it);
  138. return table_def;
  139. }
  140. ErrorOr<Vector<Row>> Database::select_all(TableDef& table)
  141. {
  142. VERIFY(m_table_cache.get(table.key().hash()).has_value());
  143. Vector<Row> ret;
  144. for (auto block_index = table.block_index(); block_index; block_index = ret.last().next_block_index())
  145. ret.append(m_serializer.deserialize_block<Row>(block_index, table, block_index));
  146. return ret;
  147. }
  148. ErrorOr<Vector<Row>> Database::match(TableDef& table, Key const& key)
  149. {
  150. VERIFY(m_table_cache.get(table.key().hash()).has_value());
  151. Vector<Row> ret;
  152. // TODO Match key against indexes defined on table. If found,
  153. // use the index instead of scanning the table.
  154. for (auto block_index = table.block_index(); block_index;) {
  155. auto row = m_serializer.deserialize_block<Row>(block_index, table, block_index);
  156. if (row.match(key))
  157. ret.append(row);
  158. block_index = ret.last().next_block_index();
  159. }
  160. return ret;
  161. }
  162. ErrorOr<void> Database::insert(Row& row)
  163. {
  164. VERIFY(m_table_cache.get(row.table().key().hash()).has_value());
  165. // TODO: implement table constraints such as unique, foreign key, etc.
  166. row.set_block_index(m_heap->request_new_block_index());
  167. row.set_next_block_index(row.table().block_index());
  168. TRY(update(row));
  169. // TODO update indexes defined on table.
  170. auto table_key = row.table().key();
  171. table_key.set_block_index(row.block_index());
  172. VERIFY(m_tables->update_key_pointer(table_key));
  173. row.table().set_block_index(row.block_index());
  174. return {};
  175. }
  176. ErrorOr<void> Database::remove(Row& row)
  177. {
  178. auto& table = row.table();
  179. VERIFY(m_table_cache.get(table.key().hash()).has_value());
  180. TRY(m_heap->free_storage(row.block_index()));
  181. if (table.block_index() == row.block_index()) {
  182. auto table_key = table.key();
  183. table_key.set_block_index(row.next_block_index());
  184. m_tables->update_key_pointer(table_key);
  185. table.set_block_index(row.next_block_index());
  186. return {};
  187. }
  188. for (auto block_index = table.block_index(); block_index;) {
  189. auto current = m_serializer.deserialize_block<Row>(block_index, table, block_index);
  190. if (current.next_block_index() == row.block_index()) {
  191. current.set_next_block_index(row.next_block_index());
  192. TRY(update(current));
  193. break;
  194. }
  195. block_index = current.next_block_index();
  196. }
  197. return {};
  198. }
  199. ErrorOr<void> Database::update(Row& tuple)
  200. {
  201. VERIFY(m_table_cache.get(tuple.table().key().hash()).has_value());
  202. // TODO: implement table constraints such as unique, foreign key, etc.
  203. m_serializer.reset();
  204. m_serializer.serialize_and_write<Tuple>(tuple);
  205. // TODO update indexes defined on table.
  206. return {};
  207. }
  208. }