Database.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2022-2024, Tim Flynn <trflynn89@serenityos.org>
  3. * Copyright (c) 2023, Jelle Raaijmakers <jelle@gmta.nl>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Error.h>
  9. #include <AK/Function.h>
  10. #include <AK/NonnullRefPtr.h>
  11. #include <AK/RefCounted.h>
  12. #include <AK/StringView.h>
  13. #include <AK/Vector.h>
  14. struct sqlite3;
  15. struct sqlite3_stmt;
  16. namespace WebView {
  17. class Database : public RefCounted<Database> {
  18. public:
  19. static ErrorOr<NonnullRefPtr<Database>> create();
  20. ~Database();
  21. using StatementID = size_t;
  22. using OnResult = Function<void(StatementID)>;
  23. ErrorOr<StatementID> prepare_statement(StringView statement);
  24. void execute_statement(StatementID, OnResult on_result);
  25. template<typename... PlaceholderValues>
  26. void execute_statement(StatementID statement_id, OnResult on_result, PlaceholderValues&&... placeholder_values)
  27. {
  28. int index = 1;
  29. (apply_placeholder(statement_id, index++, forward<PlaceholderValues>(placeholder_values)), ...);
  30. execute_statement(statement_id, move(on_result));
  31. }
  32. template<typename ValueType>
  33. ValueType result_column(StatementID, int column);
  34. private:
  35. explicit Database(sqlite3*);
  36. template<typename ValueType>
  37. void apply_placeholder(StatementID statement_id, int index, ValueType const& value);
  38. ALWAYS_INLINE sqlite3_stmt* prepared_statement(StatementID statement_id)
  39. {
  40. VERIFY(statement_id < m_prepared_statements.size());
  41. return m_prepared_statements[statement_id];
  42. }
  43. sqlite3* m_database { nullptr };
  44. Vector<sqlite3_stmt*> m_prepared_statements;
  45. };
  46. }