DBResult_ptr Database::verifyResult(DBResult_ptr result)
{
	if (!result->hasNext()) {
		return nullptr;
	}
	return result;
}
DBResult_ptr Database::storeQuery(const std::string& query)
{
	// executes the query
	database_lock.lock();

	retry:
	while (mysql_real_query(m_handle, query.c_str(), query.length()) != 0) {
		std::cout << "[Error - mysql_real_query] Query: " << query << std::endl << "Message: " << mysql_error(m_handle) << std::endl;
		auto error = mysql_errno(m_handle);
		if (error != CR_SERVER_LOST && error != CR_SERVER_GONE_ERROR && error != CR_CONN_HOST_ERROR && error != 1053/*ER_SERVER_SHUTDOWN*/ && error != CR_CONNECTION_ERROR) {
			break;
		}
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}

	// we should call that every time as someone would call executeQuery('SELECT...')
	// as it is described in MySQL manual: "it doesn't hurt" :P
	MYSQL_RES* m_res = mysql_store_result(m_handle);

	// error occured
	if (!m_res) {
		std::cout << "[Error - mysql_store_result] Query: " << query << std::endl << "Message: " << mysql_error(m_handle) << std::endl;
		int error = mysql_errno(m_handle);
		if (error != CR_SERVER_LOST && error != CR_SERVER_GONE_ERROR && error != CR_CONN_HOST_ERROR && error != 1053/*ER_SERVER_SHUTDOWN*/ && error != CR_CONNECTION_ERROR) {
			database_lock.unlock();
			return nullptr;
		}
		goto retry;
	}
	database_lock.unlock();

	// retriving results of query
	DBResult_ptr result = DBResult_ptr(new DBResult(m_res));
	if (!result->hasNext()) {
		return nullptr;
	}
	return result;
}