DatabaseConnection.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/LexicalPath.h>
  7. #include <SQLServer/DatabaseConnection.h>
  8. #include <SQLServer/SQLStatement.h>
  9. namespace SQLServer {
  10. static HashMap<u64, NonnullRefPtr<DatabaseConnection>> s_connections;
  11. static u64 s_next_connection_id = 0;
  12. RefPtr<DatabaseConnection> DatabaseConnection::connection_for(u64 connection_id)
  13. {
  14. if (s_connections.contains(connection_id))
  15. return *s_connections.get(connection_id).value();
  16. dbgln_if(SQLSERVER_DEBUG, "Invalid connection_id {}", connection_id);
  17. return nullptr;
  18. }
  19. ErrorOr<NonnullRefPtr<DatabaseConnection>> DatabaseConnection::create(DeprecatedString database_name, int client_id)
  20. {
  21. if (LexicalPath path(database_name); (path.title() != database_name) || (path.dirname() != "."))
  22. return Error::from_string_view("Invalid database name"sv);
  23. auto database = SQL::Database::construct(DeprecatedString::formatted("/home/anon/sql/{}.db", database_name));
  24. if (auto result = database->open(); result.is_error()) {
  25. warnln("Could not open database: {}", result.error().error_string());
  26. return Error::from_string_view("Could not open database"sv);
  27. }
  28. return adopt_nonnull_ref_or_enomem(new (nothrow) DatabaseConnection(move(database), move(database_name), client_id));
  29. }
  30. DatabaseConnection::DatabaseConnection(NonnullRefPtr<SQL::Database> database, DeprecatedString database_name, int client_id)
  31. : Object()
  32. , m_database(move(database))
  33. , m_database_name(move(database_name))
  34. , m_connection_id(s_next_connection_id++)
  35. , m_client_id(client_id)
  36. {
  37. dbgln_if(SQLSERVER_DEBUG, "DatabaseConnection {} initiatedconnection with database '{}'", connection_id(), m_database_name);
  38. s_connections.set(m_connection_id, *this);
  39. }
  40. void DatabaseConnection::disconnect()
  41. {
  42. dbgln_if(SQLSERVER_DEBUG, "DatabaseConnection::disconnect(connection_id {}, database '{}'", connection_id(), m_database_name);
  43. s_connections.remove(connection_id());
  44. }
  45. SQL::ResultOr<u64> DatabaseConnection::prepare_statement(StringView sql)
  46. {
  47. dbgln_if(SQLSERVER_DEBUG, "DatabaseConnection::prepare_statement(connection_id {}, database '{}', sql '{}'", connection_id(), m_database_name, sql);
  48. auto statement = TRY(SQLStatement::create(*this, sql));
  49. return statement->statement_id();
  50. }
  51. }