Question

I am working on protection to a database access object in my project, which is written in C++ and connecting to MySQL (Using MySQL C API).

The project is a server-side application running 24x7.

The protection I needed is to make sure the database connection is healthy before every operation. If DAO is disconnected from database or the connection is timeout, I will have to pause the operation and wait until reconnect success.

My current design is:

class DAO 
{
public:
    int Conn(string svr, string port, string usr, string pwd, string schema); 
    int Close(); 

    // Methods for database manipulation
    int QueryXXX( ... );
    int InsertYYY( ... );
    int UpdateZZZ ( ... );

private:
    MYSQL* m_conn;
}

(I try to make it simple here )
(And for every new features manipulating new data, I simply add more methods to it.)

Base on the above design, I will have to add the checking code in the start of every methods, and I need to remind myself and other developers to add the same code in every new methods in the future.

Is there any better solution than copying the same code (or calling same function) at the staring of every single methods?

Thanks!

Was it helpful?

Solution

Here is one option: instead of placing the connection verification logic in the DAO class, move it into a separate class that encapsulates the MYSQL pointer. So something like:

class DAO {
    public:
       ...
    private:
       MyMYSQLHandleAccessWrapper m_conn;
};

class MyMYSQLHandleAccessWrapper {
    public:
       ...
       MYSQL* GetHandle() {
          // TODO: place verification logic here
          return m_conn;
       };
       ...
    private:
        ...
        MYSQL* m_conn;
};

Now, the logic in DAO that would have directly accessed m_conn will access m_conn.GetHandle(), which can implement the connection logic. So, e.g. instead of QueryXXX looking like:

DAO::QueryXXX(...) {
   check_connection(..);
   do_stuff_with_mysql(m_conn);
}

You would have:

DAO::QueryXXX(...) {
   MYSQL* mysql = m_conn.GetHandle();
   do_stuff_with_mysql(mysql);
}

It's not that different, but it forces the implementer of functions like QueryXXX to invoke the connection logic by requiring a call to GetHandle before being able to do anything with the underlying MYSQL API.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top