Database.cpp 7.9 KB

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