Database.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. #pragma once
  8. #include <AK/ByteString.h>
  9. #include <AK/NonnullRefPtr.h>
  10. #include <AK/RefPtr.h>
  11. #include <LibSQL/Forward.h>
  12. #include <LibSQL/Heap.h>
  13. #include <LibSQL/Meta.h>
  14. #include <LibSQL/Result.h>
  15. #include <LibSQL/Serializer.h>
  16. namespace SQL {
  17. /**
  18. * A Database object logically connects a Heap with the SQL data we want
  19. * to store in it. It has BTree pointers for B-Trees holding the definitions
  20. * of tables, columns, indexes, and other SQL objects.
  21. */
  22. class Database : public RefCounted<Database> {
  23. public:
  24. static ErrorOr<NonnullRefPtr<Database>> create(ByteString);
  25. ~Database();
  26. ResultOr<void> open();
  27. bool is_open() const { return m_open; }
  28. ErrorOr<void> commit();
  29. ErrorOr<size_t> file_size_in_bytes() const { return m_heap->file_size_in_bytes(); }
  30. ResultOr<void> add_schema(SchemaDef const&);
  31. static Key get_schema_key(ByteString const&);
  32. ResultOr<NonnullRefPtr<SchemaDef>> get_schema(ByteString const&);
  33. ResultOr<void> add_table(TableDef& table);
  34. static Key get_table_key(ByteString const&, ByteString const&);
  35. ResultOr<NonnullRefPtr<TableDef>> get_table(ByteString const&, ByteString const&);
  36. ErrorOr<Vector<Row>> select_all(TableDef&);
  37. ErrorOr<Vector<Row>> match(TableDef&, Key const&);
  38. ErrorOr<void> insert(Row&);
  39. ErrorOr<void> remove(Row&);
  40. ErrorOr<void> update(Row&);
  41. private:
  42. explicit Database(NonnullRefPtr<Heap>);
  43. bool m_open { false };
  44. NonnullRefPtr<Heap> m_heap;
  45. Serializer m_serializer;
  46. RefPtr<BTree> m_schemas;
  47. RefPtr<BTree> m_tables;
  48. RefPtr<BTree> m_table_columns;
  49. HashMap<u32, NonnullRefPtr<SchemaDef>> m_schema_cache;
  50. HashMap<u32, NonnullRefPtr<TableDef>> m_table_cache;
  51. };
  52. }