BF2MC-Matchmaker
chat.cpp
1 #include <iostream>
2 #include <mysql/mysql.h>
3 
4 #include <settings.h>
5 #include <logger.h>
6 #include <util.h>
7 
8 #include <database.h>
9 
10 bool Database::insertChat(int profileid, const std::string& ip, int target_profileid, const std::string& message)
11 {
12  std::lock_guard<std::mutex> guard(this->_mutex); // database lock
13 
14  std::string query = "";
15  query += "INSERT INTO `Chat` ";
16  query += " (`profileid`, `ip`, `target_profileid`, `message`) ";
17  query += "VALUES ";
18  query += " (?, ?, ?, ?)";
19 
20  // Allocate input binds
21  MYSQL_BIND* input_bind = (MYSQL_BIND *)calloc(4, sizeof(MYSQL_BIND));
22  input_bind[0].buffer_type = MYSQL_TYPE_LONG;
23  input_bind[0].buffer = &profileid;
24  input_bind[0].is_unsigned = false;
25  input_bind[1].buffer_type = MYSQL_TYPE_STRING;
26  input_bind[1].buffer = const_cast<char*>(&(ip[0]));
27  input_bind[1].buffer_length = ip.size();
28  input_bind[2].buffer_type = MYSQL_TYPE_LONG;
29  input_bind[2].buffer = &target_profileid;
30  input_bind[2].is_unsigned = false;
31  input_bind[3].buffer_type = MYSQL_TYPE_STRING;
32  input_bind[3].buffer = const_cast<char*>(&(message[0]));
33  input_bind[3].buffer_length = message.size();
34 
35  // Prepare and execute with binds
36  MYSQL_STMT* statement;
37 
38  if(
39  !this->_init(&statement) ||
40  !this->_prepare(statement, query, input_bind) ||
41  !this->_execute(statement)
42  )
43  {
44  // Cleanup
45  free(input_bind);
46 
47  return false;
48  }
49 
50  // Cleanup
51  mysql_stmt_free_result(statement);
52  mysql_stmt_close(statement);
53  free(input_bind);
54 
55  return true;
56 }
bool _prepare(MYSQL_STMT *statement, const std::string &query)
Prepares a MySQL statement with a query.
Definition: database.cpp:59
bool _init(MYSQL_STMT **statement)
Initializes a MySQL statement object.
Definition: database.cpp:45
bool _execute(MYSQL_STMT *statement)
Executes a prepared MySQL statement.
Definition: database.cpp:94
std::mutex _mutex
Mutex for thread-safe access to the database connection.
Definition: database.h:42
bool insertChat(int profileid, const std::string &ip, int target_profileid, const std::string &msg)
Inserts a chat message into the database.
Definition: chat.cpp:10